QT学习_录音功能

Posted Leslie X徐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了QT学习_录音功能相关的知识,希望对你有一定的参考价值。

QT音频输入

使用QAudioRecorder录音

界面:
在这里插入图片描述

使用到的类:
录制:

  • QAudioRecorder:用于录制音频的类
  • QAudioEncoderSettings:对输入音频设置,主要是编码格式、采样率、通道数、音频质量等高级设置。
    播放:
  • QMediaPlayer
  • QMediaPlaylist

代码功能实现:
头文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QAudioRecorder>
#include <QFileDialog>
#include <QMessageBox>
#include <QUrl>
#include <QMediaPlayer>
#include <QMediaPlaylist>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

    QAudioRecorder *recorder;

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private slots:
    void onStateChanged(QMediaRecorder::State state);
    void onDurationChanged(qint64 duration);

    void on_actionRecordStop_triggered();

    void on_actionRecordPause_triggered();

    void on_actionQuit_triggered();

    void on_actionRecordStart_triggered();

    void on_btnsavefile_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H


构造函数

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    
    player = new QMediaPlayer(this);
    playlist = new QMediaPlaylist(this);
    player->setPlaylist(playlist);

    recorder = new QAudioRecorder(this);

    connect(recorder,&QAudioRecorder::stateChanged,
            this,&MainWindow::onStateChanged);
    connect(recorder,&QAudioRecorder::durationChanged,
            this,&MainWindow::onDurationChanged);

    if(recorder->defaultAudioInput().isEmpty()) return;

    //设置选项
    for(const QString &device : recorder->audioInputs())
        ui->cbinput->addItem(device);
    for(const QString &codeName : recorder->supportedAudioCodecs())
        ui->cbencode->addItem(codeName);
    for(int sampleRate : recorder->supportedAudiosampleRates())
        ui->cbsample->addItem(QString::number(sampleRate));
    //channels
    QStringList channels;
    channels<<"1"<<"2"<<"4";
    ui->cbchannel->addItems(channels);
    //bitrates
    QStringList bitrates;
    bitrates<<"32000"<<"64000"<<"96000"<<"128000";
    ui->cbchannel->addItems(bitrates);
    //quality
    ui->sliderquality->setRange(0,int(QMultimedia::VeryHighQuality));
    ui->sliderquality->setValue(int(QMultimedia::NormalQuality));

	//根据自己配置预设
    ui->cbencode->setCurrentIndex(4);
    ui->cbsample->setCurrentIndex(1);
    ui->editfile->setText(QDir::homePath()+"/out.wav");
}

补充知识:QString中使用arg


  QString i;           // current file's number
  QString total;       // number of files to process
  QString fileName;    // current file's name

  QString status = QString("Processing file %1 of %2: %3")
                  .arg(i).arg(total).arg(fileName);

菜单工具栏等状态变化槽函数:

void MainWindow::onStateChanged(QMediaRecorder::State state)
{
    ui->actionRecordStart->setEnabled(state!=QMediaRecorder::RecordingState);
    ui->actionRecordPause->setEnabled(state==QMediaRecorder::RecordingState);
    ui->actionRecordStop->setEnabled(state==QMediaRecorder::RecordingState);
    ui->btnsavefile->setEnabled(state!=QMediaRecorder::RecordingState);
    ui->editfile->setEnabled(state!=QMediaRecorder::RecordingState);
}

void MainWindow::onDurationChanged(qint64 duration)
{
    ui->labperiod->setText(QString("period: %1 s").arg(duration/1000));
}

录音功能:


//开始音频设置
recorder->setOutputLocation(QUrl::fromLocalFile(f));
recorder->setAudioInput(ui->cbinput->currentText());

QAudioEncoderSettings settings;
settings.setCodec(ui->cbencode->currentText());
settings.setSampleRate(ui->cbsample->currentText().toInt());
settings.setBitRate(ui->cbbitrate->currentText().toInt());
settings.setChannelCount(ui->cbchannel->currentText().toInt());
settings.setQuality(QMultimedia::EncodingQuality(
                        ui->sliderquality->value()));
if(ui->rbquality->isChecked())
    settings.setEncodingMode(QMultimedia::ConstantQualityEncoding);
else
    settings.setEncodingMode(QMultimedia::ConstantBitRateEncoding);

recorder->setAudioSettings(settings);

保存文件功能:

void MainWindow::on_btnsavefile_clicked()
{
    QString curPath = QDir::homePath();
    QString dlgTitle = "Save File";
    QString filter = "audio file(*.wav) ";
    QString fileName = QFileDialog::getSaveFileName(
                this,dlgTitle,curPath,filter);
    if(!fileName.isEmpty())
    ui->editfile->setText(fileName);
}

播放功能:

void MainWindow::on_pushButton_clicked()
{
    playlist->addMedia(QUrl::fromLocalFile(ui->editfile->text().trimmed()));
    playlist->setCurrentIndex(0);
    player->play();
}

代码

头文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QAudioRecorder>
#include <QFileDialog>
#include <QMessageBox>
#include <QUrl>
#include <QMediaPlayer>
#include <QMediaPlaylist>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

    QAudioRecorder *recorder;
    QMediaPlayer *player;
    QMediaPlaylist *playlist;

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private slots:
    void onStateChanged(QMediaRecorder::State state);
    void onDurationChanged(qint64 duration);

    void on_actionRecordStop_triggered();

    void on_actionRecordPause_triggered();

    void on_actionQuit_triggered();

    void on_actionRecordStart_triggered();

    void on_btnsavefile_clicked();

    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

源文件

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    recorder = new QAudioRecorder(this);
    
    player = new QMediaPlayer(this);
    playlist = new QMediaPlaylist(this);
    player->setPlaylist(playlist);

    connect(recorder,&QAudioRecorder::stateChanged,
            this,&MainWindow::onStateChanged);
    connect(recorder,&QAudioRecorder::durationChanged,
            this,&MainWindow::onDurationChanged);

    if(recorder->defaultAudioInput().isEmpty()) return;

    //设置选项
    foreach(const QString &device , recorder->audioInputs())
        ui->cbinput->addItem(device);
    foreach(const QString &codeName , recorder->supportedAudioCodecs())
        ui->cbencode->addItem(codeName);
    //sampleRate
    QStringList samplerates;
    samplerates<<"8000"<<"44100"<<"96000";
    ui->cbsample->addItems(samplerates);
    //channels
    QStringList channels;
    channels<<"1"<<"2"<<"4";
    ui->cbchannel->addItems(channels);
    //bitrates
    QStringList bitrates;
    bitrates<<"32000"<<"64000"<<"96000"<<"128000";
    ui->cbbitrate->addItems(bitrates);
    //quality
    ui->sliderquality->setRange(0,int(QMultimedia::VeryHighQuality));
    ui->sliderquality->setValue(int(QMultimedia::NormalQuality));

    //自己设置
    ui->cbencode->setCurrentIndex(4);
    ui->cbsample->setCurrentIndex(1);
    ui->editfile->setText(QDir::homePath()+"/out.wav");


}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onStateChanged(QMediaRecorder::State state)
{
    ui->actionRecordStart->setEnabled(state!=QMediaRecorder::RecordingState);
    ui->actionRecordPause->setEnabled(state==QMediaRecorder::RecordingState);
    ui->actionRecordStop->setEnabled(state==QMediaRecorder::RecordingState);
    ui->btnsavefile->setEnabled(state!=QMediaRecorder::RecordingState);
    ui->editfile->setEnabled(state!=QMediaRecorder::RecordingState);
}

void MainWindow::onDurationChanged(qint64 duration)
{
    ui->labperiod->setText(QString("period: %1 s").arg(duration/1000));
}

void MainWindow::on_actionRecordStop_triggered()
{
    recorder->stop();
}

void MainWindow::on_actionRecordPause_triggered()
{
    recorder->pause();
}

void MainWindow::on_actionQuit_triggered()
{
    recorder->stop();
    this->close();
}

void MainWindow::on_actionRecordStart_triggered()
{
    if(recorder->state()==QMediaRecorder::StoppedState)
    {
        //保存路径相关设置
        QString f = ui->editfile->text().trimmed();
        if(f.isEmpty()){
            QMessageBox::critical(this,"error","please set saveFile path");
            return;
        }
        if(QFile::exists(f))
            if(!QFile::remove(f)){
                QMessageBox::critical(this,"error","can't remove origin file");
                return;
            }

        //开始音频设置
        recorder->setOutputLocation(QUrl::fromLocalFile(f));
        recorder->setAudioInput(ui->cbinput->currentText());

        QAudioEncoderSettings settings;
        settings.setCodec(ui->cbencode->currentText());
        settings.setSampleRate(ui->cbsample->currentText().toInt());
        settings.setBitRate(ui->cbbitrate->currentText().toInt());
        settings.setChannelCount(ui->cbchannel->currentText().toInt());
        settings.setQuality(QMultimedia::EncodingQuality(
                                ui->sliderquality->value()));
        if(ui->rbquality->isChecked())
            settings.setEncodingMode(QMultimedia::ConstantQualityEncoding);
        else
            settings.setEncodingMode(QMultimedia::ConstantBitRateEncoding);

        recorder->setAudioSettings(settings);
    }

    recorder->record();
}

void MainWindow::on_btnsavefile_clicked()
{
    QString curPath = QDir::homePath();
    QString dlgTitle = "Save File";
    QString filter = "audio file(*.wav) ";
    QString fileName = QFileDialog::getSaveFileName(
                this,dlgTitle,curPath,filter);
    if(!fileName.isEmpty())
    ui->editfile->setText(fileName);
}

void MainWindow::on_pushButton_clicked()
{
    playlist->addMedia(QUrl::fromLocalFile(ui->editfile->text().trimmed()));
    playlist->setCurrentIndex(0);
    player->play();
}

以上是关于QT学习_录音功能的主要内容,如果未能解决你的问题,请参考以下文章

Qt文档阅读笔记-Qt5录音功能的实现

QT 实用代码片段

Android学习之路-录音功能实现

QT学习记录QT基本功能

QT学习_QT实现拖拽功能

python2根据索引表查找相应的录音片段拼接录音