2017-07-15 70 views

回答

2

你并不真的需要同步播放声音。任何可能阻止GUI线程超过0.10秒不应该做在那里,有更多的信息,看看here

既然你愿意,当用户点击退出按钮播放声音,我觉得用QSoundEffect是你的情况比较好,从docs

该类允许你播放无压缩的音频文件在大体较低延迟的方式(通常为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(); 
} 
+0

问题用QSoundEffect解决,谢谢。 –