I can not get the QSoundEffect
to play in a separate thread. Could you please tell me why is the sound played only by the first code snippet and not by the second?
//main.cpp
#include <QCoreApplication>
#include "SoundThread.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// #1
QSoundEffect alarmSound;
alarmSound.setSource(QUrl::fromLocalFile(":/sound"));
alarmSound.play();
/* #2
SoundThread thread;
thread.start();
thread.wait();
*/
return a.exec();
}
and
//SoundThread.h
#ifndef SOUNDTHREAD_H
#define SOUNDTHREAD_H
#include <QThread>
#include <QtMultimedia/QSoundEffect>
class SoundThread : public QThread
{
Q_OBJECT
private:
void run()
{
QSoundEffect alarmSound;
alarmSound.setSource(QUrl::fromLocalFile(":/sound"));
alarmSound.play();
while(true){}
}
};
#endif // SOUNDTHREAD_H
Replace
while(true){}
byQThread::run();
, which will launch an internal event loop and will wait (sleep) for events, such as timer events and asynchronous signals calling slots, which is probably what is happening internally inQSoundEffect
: When you callQSoundEffect::play()
Some event (probably signals/slots) are queued in the event queue from withinQThread
, but nothing is processing the event queue. Remember: you are overridingvirtual void run()
and the original implementation was callingQThread::exec()
for you. It is always a good idea to always call your super classes virtual function whenever you override them, as long as they are not pure virtual.Some people suggested that calling
QThread::exec()
would do the trick. They may be right. I have to check the implementation of QThread to confirm that it is the only thing called inQThread::run()
implementation. I personally think (by experience) that it is always safer to call your superclasse's virtual function in case there are other things called (other thanQThread::exec()
for this particular case).Another option would be to move your QSoundEffect instance onto the thread and use signals and slots default auto-connection behaviour type to switch threads.
SoundPlayer.h:
SoundPlayer.cpp :
And then calling the play() signal would start playing in the correct thread.