如何使用QMediaPlayer播放流式音频?

时间:2014-10-15 10:39:49

标签: c++ qt audio-streaming qtmultimedia qmediaplayer

我有来自服务器的音频流,我想在我的程序中使用QMediaPlayer。当我第一次将文件下载到QBuffer,然后从播放器调用setMediaplay方法时,一切正常。但是,如果我想在流仍在工作时播放音乐,则媒体播放器仅在调用setMedia方法然后停止时播放声音。 有没有什么方法可以让它像我想的那样工作?谢谢。

2 个答案:

答案 0 :(得分:2)

如果你以正确的方式初始化播放器,我认为没有理由不工作。

由于您还没有共享您编写的代码(因为如果我发表评论,我将在当天剩下的时间内无法查看您的回复),我将在此处留下一些示例代码。 看看下面的代码是否适合您。

QMediaPlayer* player = new QMediaPlayer(this, QMediaPlayer::StreamPlayback);
player->setMedia(QUrl("http://vpr.streamguys.net/vpr64.mp3"));
player->setVolume(80);
player->play();

如果是,请通过将网址更改为您的网址来尝试相同的操作。

编辑:我假设播放器在更新之前耗尽了缓冲区。请密切关注bufferStatusQMediaPlayer::MediaStatus。 我引用了documentation

bufferStatus : const int

This property holds the percentage of the temporary buffer filled before playback begins or resumes, from (empty) to (full). When the player object is buffering; this property holds the percentage of the temporary buffer that is filled. The buffer will need to reach 100% filled before playback can start or resume, at which time mediaStatus() will return BufferedMedia or BufferingMedia. If the value is anything lower than 100, mediaStatus() will return StalledMedia.

答案 1 :(得分:0)

通过QAudioOutput:

    QByteArray* yourSoundData = blah blah...;
    QBuffer* buffer = new QBuffer;
    buffer->setData(yourSoundData);
    buffer->open(QBuffer::ReadOnly);

    QAudioFormat format; // According to your sound format (e.g. wav)
    format.setSampleRate(22050);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/wav");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
    if (!info.isFormatSupported(format)) {
        qWarning() << "Raw audio format not supported by backend, cannot play audio.";
        return;
    }

    QAudioOutput* audio = new QAudioOutput(format, this);
    audio->start(buffer);

更多信息:http://doc.qt.io/qt-5/qaudiooutput.html

相关问题