问题
In Qt4 I used to use
QT += multimedia phonon
//...
#include <Phonon>
//...
Phonon::MediaObject *mediaObject = Phonon::createPlayer(Phonon::NoCategory, Phonon::MediaSource(QUrl("./assets/audio/window_appear.wav")));
// "\"" + Qdir().absolutePath() + "/audio/click.wav" + "\""
mediaObject->play();
and it all worked fine. But now Phonon is not supported in Qt 5. So I wonder - how can I play media files such as sound in Qt5?
Using WebKit? (It is entirely possible but looks kind of bad from many points of view)
回答1:
The Qt developers started to reduce their efforts on Phonon integration already during the later versions of Qt4, focussing on the Qt Multimedia and Qt Mobility modules instead. Though they did still support Phonon.
As you say, as of Qt5, Phonon is no longer supported. So look into Qt Multimedia instead, especially QAudioOutput.
As listed within their documentation under "Detailed Description", playing an audio file looks something like this:
QFile inputFile; // class member.
QAudioOutput* audio; // class member.
inputFile.setFileName("/tmp/test.raw");
inputFile.open(QIODevice::ReadOnly);
QAudioFormat format;
// Set up the format, eg.
format.setFrequency(8000);
format.setChannels(1);
format.setSampleSize(8);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);
QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
if (!info.isFormatSupported(format)) {
qWarning()<<"raw audio format not supported by backend, cannot play audio.";
return;
}
audio = new QAudioOutput(format, this);
connect(audio,SIGNAL(stateChanged(QAudio::State)),SLOT(finishedPlaying(QAudio::State)));
audio->start(&inputFile);
来源:https://stackoverflow.com/questions/14296326/how-to-play-sound-in-qt5-qt4-migration