Search code examples
c++qtqt-designerqmediaplayer

QMediaPlayer don't play before Sleep


I'm making a proyect in Qt Designer and I'm trying to play sound before a Sleep. I have a pushButton with a on_clicked where it first play the QMediaPlayer and then sleeps for 2 seconds, but the sound is played after the 2 seconds instead of before. This is the code on the pushButton:

void ScreenCombate::on_usar1_clicked()
{

    mediaplayer2 = new QMediaPlayer(this);
    mediaplayer2->setMedia(QUrl("qrc:/mini/sword.mp3"));
    mediaplayer2->setVolume(100);
    mediaplayer2->play();

    Sleep(1500);
}

Does anyone know how to solve that?


Solution

  • You are blocking the main event loop by sleeping which causes playing happen when control returns back to event loop. You should never block main event loop or your UI and other stuff would freeze while sleeping. If you really want to wait somewhere in your code, it's better to use a local event loop and wait there:

    QEventLoop loop;
    QTimer timer;
    QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
    timer.start(1500);
    loop.exec();
    

    But you should note that it's not a good practice and you are better to make things async using signals and slots.