本文主要是介绍Qt实现麦克风音频输入保存wav文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一.本文目的
实现在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));
}
三.工程代码下载
https://download.csdn.net/download/xieliru/89398205
这篇关于Qt实现麦克风音频输入保存wav文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!