【问题标题】:Qt 5 Play wav sound while input from userQt 5在用户输入时播放wav声音
【发布时间】:2018-04-19 19:53:02
【问题描述】:

当事情发生时,我的程序会提醒用户。为了引起他的注意,会发出警报声。当用户输入内容以确认收据时,它会停止。

但是 QTextStream 输入会阻塞声音! 当我移除它时,声音播放完美。

此外,“警报”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 是否为阻塞操作的信息。在readLine 开始接受输入之前,声音是否会播放一次,直到 wav 文件结束?编辑:看看这个线程stackoverflow.com/questions/5600515/…
  • 声音播放一次,直到 wav 文件结束,但 readLine 接受输入之后,而不是之前。就像 readLine 的优先级高于 QSound::play()。
  • 谢谢! QMediaPlayer 也可以! #include &lt;QtMultimedia/QMediaPlayer&gt; QMediaPlayer *player = new QMediaPlayer; player-&gt;setMedia(QUrl::fromLocalFile("/path")); player-&gt;setVolume(50); player-&gt;play();

标签: c++ qt input wav


【解决方案1】:

QSound::play 是异步的,但是

QString value = s.readLine();

包含一个do-while,将阻止音频文件。参见scan function 调用的readLine()

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();
}

【讨论】:

  • 非常感谢这个例子!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多