本页内容

音频录制示例

检测可用设备和支持的编解码器。

“音频录制器”示例演示了如何识别可用设备和受支持的编解码器,以及如何使用 QAudioRecorder 类。

用于选择音频输入、编解码器和格式类型的设置面板

运行示例

您可以通过以下方式运行该示例:

显示窗口和音频设置

我们会显示一个窗口,供用户选择合适的音频输入、编解码器、容器格式、采样率和声道。该窗口支持设置音质或比特率。最后,用户可以选择输出文件并开始录制。

列表内容通过以下方法填充:

质量滑块的范围设置为0(零)至QMediaRecorder::VeryHighQuality ,默认值为QMediaRecorder::NormalQuality ;而比特率选项框中的数值则是硬编码到列表中的。

录制音频

要录制音频,我们只需创建一个 QAudioRecorder 对象,

audioRecorder = new QAudioRecorder(this);

并按上述说明配置列表。 “录制”和“暂停”按钮上的文字会根据audioRecorder 对象的state 状态进行切换。这意味着,如果状态为QMediaRecorder::StoppedState ,则按钮文字将显示为“录制”和“暂停”。在QMediaRecorder::RecordingState 状态下,录制按钮将显示“停止”文字;而在QMediaRecorder::PausedState 状态下,暂停按钮将显示“继续”文字。

按下按钮还会根据当前状态触发状态切换。如果录制已停止,则按下录制按钮将设置audioRecorder 对象的编码设置和容器,并通过record() 方法开始录制。

QMediaFormat format;
format.setCodec(boxValue(ui->audioCodecBox).toString());
audioRecorder->setMediaFormat(format);
audioRecorder->setSampleRate(boxValue(ui->sampleRateBox).toInt());
audioRecorder->setBitRate(boxValue(ui->bitrateBox).toInt());
audioRecorder->setQuality(QMediaRecorder::EncodingQuality(ui->qualitySlider->value()));
audioRecorder->setEncodingMode(ui->constantQualityRadioButton->isChecked() ?
                         QMediaRecorder::ConstantQualityEncoding :
                         QMediaRecorder::ConstantBitRateEncoding);

QString container = boxValue(ui->containerBox).toString();

audioRecorder->record();

录制期间,应用程序的状态栏会根据来自audioRecorder 对象的durationChanged 信号,实时更新时长信息。

ui->statusbar->showMessage(tr("Recorded %1 sec").arg(duration / 1000));

示例项目 @ code.qt.io

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.