Luca Bonaldo
Luca Bonaldo

Reputation: 15

How to play a sound before splash in QT?

I want to play a sound within the splash but with the following code I get the splash to show up and then, only when the splash is gone, the sound to play. Can someone help me out? Thank you very much.

    QApplication a(argc, argv);

    QMediaPlayer * splashSound = new QMediaPlayer;
    splashSound->setMedia(QUrl("qrc:/sfx/splash_sound.wav"));
    splashSound->play();

    QSplashScreen * mainSplash = new QSplashScreen;
    mainSplash->setPixmap(QPixmap(":/img/splash.png"));
    mainSplash->show();

    MainWindow w;

    QTimer::singleShot(2500, mainSplash, SLOT(close()));
    QThread::msleep(2500);

    w.show();

    return a.exec();

Upvotes: 2

Views: 92

Answers (1)

Jeremy Friesner
Jeremy Friesner

Reputation: 73061

The problem is your call to QThread::msleep(2500); it prevents the Qt event loop from executing (because a.exec() can't run until after it returns), and that in turn prevents the audio from playing.

The easy fix is to remove that line and the call to w.show(), and replace them with something like this:

QTimer::singleShot(2500, &w, SLOT(show()));

... That will cause your MainWindow widget to appear at the same time the splash-image disappears.

Upvotes: 3

Related Questions