一.本文 目的
实现在Qt中接收麦克风数据并保存为WAV文件,使用QAudioInput来录音,并使用QFile来保存数据到WAV文件。
开发环境:QT5.12
本文用极简代码实现,核心代码只需不到100行。
完整工程代码文末链接可以直接下载。
二.代码实现
(1)main.cpp
#include "audiorecorder.h"
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
AudioRecorder recorder;
recorder.show();
return app.exec();
}
2.audiorecorder.h
#ifndef AUDIORECORDER_H
#define AUDIORECORDER_H
#include <QMainWindow>
#include <QMediaRecorder>
#include <QUrl>
QT_BEGIN_NAMESPACE
namespace Ui { class AudioRecorder; }
class QAudioRecorder;
class QAudioProbe;
QT_END_NAMESPACE
class AudioRecorder : public QMainWindow
{
Q_OBJECT
public:
AudioRecorder();
private slots:
void on_outputButton_clicked();
void on_recordButton_clicked();
void updateProgress(qint64 pos);
private:
Ui::AudioRecorder *ui = nullptr;
QAudioRecorder *m_audioRecorder = nullptr;
QAudioProbe *m_probe = nullptr;
};
#endif // AUDIORECORDER_H
3.audiorecorder.cpp
#include "audiorecorder.h"
#include "ui_audiorecorder.h"
#include <QAudioProbe>
#include <QAudioRecorder>
#include <QDir>
#include <QFileDialog>
#include <QMediaRecorder>
#include <QStandardPaths>
AudioRecorder::AudioRecorder()
: ui(new Ui::AudioRecorder)
{
ui->setupUi(this);
m_audioRecorder = new QAudioRecorder(this);
m_probe = new QAudioProbe(this);
m_probe->setSource(m_audioRecorder);
//audio devices
ui->audioDeviceBox->addItem(tr("Default"), QVariant(QString()));
for (auto &device: m_audioRecorder->audioInputs()) {
ui->audioDeviceBox->addItem(device, QVariant(device));
qDebug()<<"device:"<<device;
}
QAudioEncoderSettings settings;
settings.setCodec("");
settings.setSampleRate(44100);
settings.setChannelCount(1); //单通道
settings.setQuality(QMultimedia::NormalQuality);
m_audioRecorder->setEncodingSettings(settings, QVideoEncoderSettings(), "audio/x-wav");
connect(m_audioRecorder, &QAudioRecorder::durationChanged, this, &AudioRecorder::updateProgress);
}
void AudioRecorder::on_outputButton_clicked()
{
QString fileName = QFileDialog::getSaveFileName();
m_audioRecorder->setOutputLocation(QUrl::fromLocalFile(fileName));
}
void AudioRecorder::on_recordButton_clicked()
{
if(ui->recordButton->text() == "Record")
{
m_audioRecorder->record();
ui->recordButton->setText("Pause");
}
else if(ui->recordButton->text() == "Pause")
{
m_audioRecorder->stop();
ui->recordButton->setText("Record");
}
}
void AudioRecorder::updateProgress(qint64 duration)
{
if (m_audioRecorder->error() != QMediaRecorder::NoError || duration < 1000)
return;
ui->statusbar->showMessage(tr("Recorded %1 sec").arg(duration / 1000));
}
三.工程代码下载