帮忙调试开发板,需要播放pcm文件,最开始搜了一下网上代码,多少都有些问题,最终还是回归了Qt的帮助文档,代码很简单,就是pcm音频数据的输出。


核心代码

pcm_file_.setFileName("file_path");
    if(pcm_file_.open(QIODevice::ReadOnly)) {
        // Set up the format, eg.
        QAudioFormat format;
        format.setSampleRate(8000);
        format.setChannelCount(1);
        format.setSampleFormat(QAudioFormat::Int16);

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

        player_.reset(new QAudioSink(format));
        connect(player_.get(), &QAudioSink::stateChanged, this, &MainWindow::onHandleStateChanged);
        player_->start(&pcm_file_);
    } else {
        QMessageBox::information(this, tr("Tips"), QString("Open failed,Please check file path:%1").arg(_path));
    }

关键步骤

  1. 打开文件
QFile pcm_file_;
pcm_file_.setFileName("path");
  1. 设置播放参数
QAudioFormat format;
format.setSampleRate(8000);
format.setChannelCount(1);
format.setSampleFormat(QAudioFormat::Int16);

这里需要根据播放文件的具体采样参数来设置。

  1. 获取有效播放设备
QAudioDevice info(QMediaDevices::defaultAudioOutput());
info.isFormatSupported(format);
  1. 播放
player_.reset(new QAudioSink(format));
player_->start(&pcm_file_);

这里使用的是QScopedPointer指针,所以有一个reset.

上述代码完全参考了Qt的帮助文档,所以以后开发还是得回归本源。

向开源和优秀的帮助文档致敬~


源代码链接

https://gitee.com/gazi1985/pcmplayer.git