如何同步制作QSound?

How to make QSound synchronously?

本文关键字:QSound 同步 何同步      更新时间:2023-10-16

如何同步制作QSound?

我有一个退出按钮。如果我单击它,我想播放声音,然后退出程序。QSound是异步的,我不知道如何同步制作。

您实际上不需要同步播放声音。任何可能阻塞 GUI 线程超过 0.10 秒的事情都不应该在那里完成,请查看此处以获取更多信息。

由于您愿意在用户单击退出按钮时播放声音,因此我认为使用QSoundEffect更适合您的情况,来自文档:

此类允许您以通常较低的延迟方式播放未压缩的音频文件(通常是 WAV 文件(,并且适用于响应用户操作的"反馈"类型声音(例如虚拟键盘声音、弹出对话框的正反馈或负反馈或游戏声音(。

QSoundEffect有一个信号playingChanged(),您可以利用它来仅在声音播放完毕后关闭应用程序。我不知道为什么QSound没有类似的信号。

下面是一个最小的示例,解释了如何做到这一点:

#include <QtWidgets>
#include <QtMultimedia>
class Widget : public QWidget {
public:
explicit Widget(QWidget* parent= nullptr):QWidget(parent) {
//set up layout
layout.addWidget(&exitButton);
//initialize sound effect with a sound file
exitSoundEffect.setSource(QUrl::fromLocalFile("soundfile.wav"));
//play sound effect when Exit is pressed
connect(&exitButton, &QPushButton::clicked, &exitSoundEffect, &QSoundEffect::play);
//close the widget when the sound effect finishes playing
connect(&exitSoundEffect, &QSoundEffect::playingChanged, this, [this]{
if(!exitSoundEffect.isPlaying()) close();
});
}
~Widget() = default;
private:
QVBoxLayout layout{this};
QPushButton exitButton{"Exit"};
QSoundEffect exitSoundEffect;
};
//sample application
int main(int argc, char* argv[]){
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}

请注意,在音效播放完成之前,上述解决方案不会关闭窗口。

另一种方法(对于应用程序用户来说似乎更敏感(是关闭窗口,在窗口关闭时播放声音,然后在播放完毕后退出应用程序。但这需要在应用程序级别关闭最后一个窗口时禁用隐式退出 (quitOnLastWindowClosed(。

由于禁用隐式退出,您必须在程序的每个可能的退出路径上添加qApp->quit();。下面是显示第二种方法的示例:

#include <QtWidgets>
#include <QtMultimedia>
class Widget : public QWidget {
public:
explicit Widget(QWidget* parent= nullptr):QWidget(parent) {
//set up layout
layout.addWidget(&exitButton);
//initialize sound effect with a sound file
exitSoundEffect.setSource(QUrl::fromLocalFile("soundfile.wav"));
//play sound effect and close widget when exit button is pressed
connect(&exitButton, &QPushButton::clicked, &exitSoundEffect, &QSoundEffect::play);
connect(&exitButton, &QPushButton::clicked, this, &Widget::close);
//quit application when the sound effect finishes playing
connect(&exitSoundEffect, &QSoundEffect::playingChanged, this, [this]{
if(!exitSoundEffect.isPlaying()) qApp->quit();
});
}
~Widget() = default;
private:
QVBoxLayout layout{this};
QPushButton exitButton{"Exit"};
QSoundEffect exitSoundEffect;
};
//sample application
int main(int argc, char* argv[]){
QApplication a(argc, argv);
//disable implicit quit when last window is closed
a.setQuitOnLastWindowClosed(false);
Widget w;
w.show();
return a.exec();
}