Qt 5 在用户输入时播放 wav 声音

Qt 5 Play wav sound while input from user

我的程序会在发生某些事情时提醒用户。为了引起他的注意,会播放提示音。当用户输入内容以确认收到时它会停止。

但是 QTextStream 输入挡住了声音! 当我删除它时,声音播放完美。

此外,"alert" QSound 对象不起作用。唯一的玩法就是使用静态函数QSound::play("file.wav")。却挡不住。

这是我的代码:

#include <QCoreApplication>
#include <QSound>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    /*
    QSound alert("../SoundAlerte/alert.wav");
    alert.setLoops(QSound::Infinite);
    alert.play();
    */

    QSound::play("../SoundAlerte/alert.wav");

    qDebug() << "ALERT";
    qDebug() << "Enter Something to confirm receipt" ;

    QTextStream s(stdin);
    QString value = s.readLine();

    qDebug() << "Received !";

    //alert.stop();

    qDebug() << "Sound stopped";

    return a.exec();
}

好像不能同时播放声音和等待输入!

您知道如何进行吗?

谢谢

QSound::play 是异步的,但是

QString value = s.readLine();

包含一个 do-while 并将阻止音频文件。请参阅 scan functionreadLine()

调用

一个可行的例子是 QtConcurrent,但是你不能停止音频文件,所以你可能想切换到真正的 QThread 方法。

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QFuture<void> future = QtConcurrent::run([]() {
        QSoundEffect effect;
        QEventLoop loop;
        effect.setSource(QUrl::fromLocalFile("C:\piano2.wav"));
        effect.setVolume(0.25f);
        effect.play();
        QObject::connect(&effect, &QSoundEffect::playingChanged, [&loop]() { qDebug() << "finished"; loop.exit(); });
        loop.exec();
    });

    QTextStream s(stdin);
    QString value = s.readLine();

    return a.exec();
}