How to play sound in Qt5 (Qt4 migration)?

myWallJSON picture myWallJSON · Jan 12, 2013 · Viewed 7.8k times · Source

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)

Answer

Bart picture Bart · Jan 12, 2013

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);