如何同步制作QSound?
How to make QSound synchronously?
如何同步制作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();
}
相关文章:
- 松弛原子与无同步情况下的记忆连贯性
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 在C++中同步线程
- 与 stdio 同步是否使程序 I/O 非交互式?
- 如何在qt中同步应用程序和显示器的刷新率?
- Windows 进程间同步类似事件?
- 当对套接字 send() 的同步调用由于连接另一端丢失而被阻止时,如何恢复?
- 将 10 个线程与原子布尔值同步
- ofstream::close() 是否在 Linux 上调用同步?
- 与Visual Studios(c ++)同步时如何组织github存储库?
- 原子获取是否与互斥锁释放同步?
- Boost (Beast) websocket:同步写入挂起
- Postgres vs MySQL:命令不同步;.
- 线程过程中的线程同步问题
- 同步读取多个 TCP 响应
- 同步两个具有不同帧速率的传感器
- 如何定期同步线程?
- 同步对多个向量进行排序
- 呼叫 QSound,它们之间有延迟 Qt C++
- 如何同步制作QSound?