使用Qt可以很方便地实现录音设备录音并保存到本地。下面是一个简单的示例代码:

#include <QCoreApplication>
#include <QAudioInput>
#include <QFile>
#include <QTimer>

class Recorder : public QObject
{
    Q_OBJECT
public:
    explicit Recorder(QObject *parent = nullptr) : QObject(parent) {}

    void startRecording()
    {
        // 设置音频输入设备参数
        QAudioFormat format;
        format.setSampleRate(44100);
        format.setChannelCount(1);
        format.setSampleSize(16);
        format.setCodec("audio/pcm");
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setSampleType(QAudioFormat::SignedInt);

        // 创建音频输入对象
        QAudioDeviceInfo info(QAudioDeviceInfo::defaultInputDevice());
        if (!info.isFormatSupported(format)) {
            qWarning() << "Default format not supported, trying to use the nearest.";
            format = info.nearestFormat(format);
        }
        audioInput = new QAudioInput(format, this);

        // 打开文件用于保存录音数据
        audioFile = new QFile("output.wav");
        audioFile->open(QIODevice::WriteOnly | QIODevice::Truncate);

        // 开始录音
        audioInput->start(audioFile);

        // 设置定时器,5秒后停止录音
        QTimer::singleShot(5000, this, [=]() {
            stopRecording();
        });
    }

    void stopRecording()
    {
        // 停止录音
        audioInput->stop();

        // 关闭文件
        audioFile->close();

        // 释放资源
        delete audioInput;
        delete audioFile;

        QCoreApplication::quit();
    }

private:
    QAudioInput *audioInput;
    QFile *audioFile;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Recorder recorder;
    recorder.startRecording();

    return a.exec();
}

#include "main.moc"

上述代码中,我们定义了一个名为Recorder的类,用于处理录音操作。在startRecording函数中,我们首先设置了音频输入设备的参数,然后创建了一个QAudioInput对象来进行录音。通过调用start函数开始录音,并将录音数据写入到一个名为output.wav的文件中。然后我们设置了一个定时器,5秒后调用stopRecording函数停止录音。

在主函数中,我们创建了一个Recorder对象,并调用startRecording函数开始录音。最后调用QCoreApplication::exec进入Qt的事件循环中。

请注意,上述代码只是一个简单示例,可能还需要进行错误处理和其他逻辑的完善

qt 实现录音设备录音5秒并保存本地

原文地址: https://www.cveoy.top/t/topic/ijyX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录