[Qt] 使用 QMediaPlayer 从QIODevice 播放音频偶尔崩溃的问题

使用QMediaPlayer播放即时生成的wav文件,为了方便与性能,直接保存在内存中播放。

    QMediaPlayer player;
    QBuffer buff;
    buff.setData(QByteArray());   // fill buffer
    buff.open(QIODevice::ReadOnly);
    player.setMedia(QMediaContent(), &buff);
    player.play();

播放有时会崩溃,时而发生,时而正常。网上找了一圈也没能找到根源。然后在文档上发现了一句话:

Note: This function returns immediately after recording the specified source of the media. It does not wait for the media to finish loading and does not check for errors. Listen for the mediaStatusChanged() and error() signals to be notified when the media is loaded and when an error occurs during loading.

原来setMedia 立即返回,不会等待媒体加载完毕。崩溃的原因应该就是有时加载快,完成了播放正常,有时加载慢未完成,播放就崩溃。
改用监听 mediaStatusChanged() 信号来播放,果然不在崩溃了。

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    ...
    connect(player, &QMediaPlayer::mediaStatusChanged, this, &MainWindow::startToPlay);
}

void MainWindow::loadWaveBuffer()
{
    QBuffer buff;
    buff.setData(...);   // fill buffer
    buff.open(QIODevice::ReadOnly);
    player.setMedia(QMediaContent(), &buff);
}

void MainWindow::startToPlay(QMediaPlayer::MediaStatus status)
{
    if(status == QMediaPlayer::LoadedMedia)
        player.play();
}

你可能感兴趣的:(Qt)