Qt播放WAV格式音訊檔案的兩種方法
阿新 • • 發佈:2019-02-04
這兩種方法都需要在.pro檔案中加入multimedia模組。
方法一、使用QAudioOutput
#include <QApplication> #include <QFile> #include <QAudioFormat> #include <QAudioOutput> int main(int argc, char *argv[]) { QApplication a(argc, argv); QFile inputFile; inputFile.setFileName("test.wav"); inputFile.open(QIODevice::ReadOnly); //設定取樣格式 QAudioFormat audioFormat; //設定取樣率 audioFormat.setSampleRate(44100); //設定通道數 audioFormat.setChannelCount(2); //設定取樣大小,一般為8位或16位 audioFormat.setSampleSize(16); //設定編碼方式 audioFormat.setCodec("audio/pcm"); //設定位元組序 audioFormat.setByteOrder(QAudioFormat::LittleEndian); //設定樣本資料型別 audioFormat.setSampleType(QAudioFormat::UnSignedInt); QAudioOutput *audio = new QAudioOutput( audioFormat, 0); audio->start(&inputFile); return a.exec(); }
注意這裡取樣率、通道數和取樣大小的設定,本例只能用來播放無損的WAV。網上很多程式碼將取樣率設定成8000、通道數設定為1、取樣大小設定為8,這樣雖然也能播放WAV,但是沒有任何其他說明,也沒提供播放所用的WAV檔案,導致很多童鞋在網上找個WAV,播放時出現“嗡嗡”聲,根本聽不清。
“什麼是無損”參考:http://blog.csdn.net/caoshangpa/article/details/51218597
“如何下載和製作無損WAV”參考:http://blog.csdn.net/caoshangpa/article/details/51218994
方法二、使用QSoundEffect#include <QApplication> #include <QSoundEffect> int main(int argc, char *argv[]) { QApplication a(argc, argv); QSoundEffect effect; effect.setSource(QUrl::fromLocalFile("test.wav")); //迴圈播放 effect.setLoopCount(QSoundEffect::Infinite); //設定音量,0-1 effect.setVolume(0.8f); effect.play(); return a.exec(); }