2017-07-15 67 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解決,謝謝。 –