How to play sound in Qt5 (Qt4 migration)?

99封情书 提交于 2019-12-10 13:54:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!