c++ 录音数据保存wav
时间: 2024-07-20 15:01:06 浏览: 143
C++实现音频录音wav格式
在C++中,录制音频数据并将其保存为WAV文件通常涉及到音频处理库,如PortAudio、FFmpeg或Xiph.org的libavcodec等。以下是一个简化的步骤概述:
1. **包含必要的库头**:首先需要引入相关的音频库头文件,比如`#include <portaudio.h>` 或 `#include <ffmpeg/avformat.h>`。
2. **初始化录音设备**:使用PortAudio库时,可以创建一个输入流(paStream),设置采样率、位深度等参数。
```cpp
PaError err = Pa_Initialize();
PaStream *stream;
...
err = Pa_OpenDefaultStream(&stream, ...);
```
3. **开始录音**:启动音频流,监听输入数据。
4. **读取和存储数据**:当有新的音频块可用时,将其读入缓冲区,并准备保存到WAV文件。
```cpp
std::vector<int16_t> audioData;
PaFrameCount framesRecorded;
while (framesRecorded > 0) {
float* inputBuffer;
PaError status = Pa_ReadStream(stream, &inputBuffer, &framesRecorded);
// 将float数据转换成int16_t,并存入audioData数组
for (PaFrameCount i = 0; i < framesRecorded; ++i) {
audioData.push_back(reinterpret_cast<int16_t>(inputBuffer[i]));
}
}
```
5. **关闭和清理资源**:完成录音后,记得关闭音频流,释放内存,并最终关闭PortAudio。
6. **保存为WAV**:使用FFmpeg或其他支持WAV的库将音频数据写入WAV文件。
```cpp
AVFormatContext *fmt_ctx = NULL;
AVWriter *writer = NULL;
AVPacket packet;
...
fmt_ctx = avformat_alloc_context();
...
avio_open(&fmt_ctx->pb, "output.wav", AVIO_FLAG_WRITE);
avformat_write_header(fmt_ctx, &av_guess_format(NULL));
// 创建一个WAV writer
writer = avformat_alloc_output_context2(NULL, NULL, "wav", NULL);
avio_closep(fmt_ctx->pb);
for (size_t i = 0; i < audioData.size(); i += 2) { // Each sample is 2 bytes (16-bit)
int16_t sample1 = audioData[i];
int16_t sample2 = audioData[i + 1];
AVSampleFormat fmt = AV_SAMPLE_FMT_S16;
AVSampleRate sample_rate = ...; // Your desired sampling rate
AVRational channel_layout = ...; // Mono or stereo layout
uint8_t data; // 2 bytes per sample in little-endian format
pack_s16le(data, sample1); // Convert to network byte order
data = static_cast<uint8_t>(sample2);
AVFrame frame;
av_frame_set_size(&frame, 2, 1, fmt, sample_rate, channel_layout);
int got_data = 0;
av_frame_fill_arrays(&frame, NULL, data, 4, got_data);
av_write_frame(writer, &frame);
}
// Close the writer and flush any remaining packets
av_write_trailer(writer);
avformat_free_context(writer);
```
7. **错误处理**:务必检查上述每个函数的返回值,因为可能会有各种错误发生。
阅读全文