遇到的问题
主线程中循环检测设备状态,存在某一个时间点或者间隔非常近的时候多个点报警的情况。报警后主线程中继续存在计算任务。
直接使用QSoundEffect
可以播放声音,但是声音出现断续的情况。
特此考虑将QSoundEffect
的播放工作放到单独线程中。
解决思路
直接将QSoundEffect
使用moveToThread()
函数,移动到独立线程中,通过信号的方式,响应play()
。
示例代码
audiothread.h:
#ifndef DLTHREAD_H
#define DLTHREAD_H
#include <QtCore>
#include <QObject>
#include <QSoundEffect>
#include <QThread>
enum VOICE_TYPE{
VOICE_POSITIVE,
VOICE_NEGATIVE,
VOICE_TEMPERATURE
};
class AudioThread : public QObject
{
Q_OBJECT
public:
AudioThread(QObject *parent = nullptr);
~AudioThread();
signals:
void doPlay();
public slots:
void play();
void play(int type);
private:
int voice_type;
QSoundEffect effect;
QThread thread;
};
#endif // DLTHREAD_H
audiothread.cpp:
#include "audiothread.h"
#include <QUrl>
AudioThread::AudioThread(QObject *parent) :
QObject(parent)
{
effect.moveToThread(&thread);
connect(this, SIGNAL(doPlay()), &effect, SLOT(play()));
thread.start();
}
AudioThread::~AudioThread()
{
if(thread.isRunning())
{
thread.terminate();
}
}
void AudioThread::play()
{
if(!effect.isPlaying())
{
effect.setSource(QUrl::fromLocalFile("./voice/temp.wav"));
effect.setLoopCount(1);
emit this->doPlay();
}
}
void AudioThread::play(int type)
{
if(effect.isPlaying())
{
return;
}
voice_type = type;
QString fileName;
switch (voice_type)
{
case VOICE_POSITIVE:
{
fileName = "positive.wav";
}
break;
case VOICE_NEGATIVE:
{
fileName = "negative.wav";
}
break;
case VOICE_TEMPERATURE:
{
fileName = "temp.wav";
}
break;
default:
{
return;
}
}
effect.setSource(QUrl::fromLocalFile("./voice/"+fileName));
effect.setLoopCount(1);
effect.setVolume(1.0f);
emit this->doPlay();
}
其他任何文件中:
AudioThread audio;
audio.play();
//audio.play(VOICE_POSITIVE);