c++将pcm裸数据转成wav
时间: 2023-07-30 07:06:01 浏览: 159
将PCM裸数据转换成WAV文件可以通过以下步骤实现:
1. 打开一个空白的WAV文件,设置文件头部信息。
2. 将PCM数据写入WAV文件。
3. 关闭WAV文件。
下面是一个C++示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <cstdint>
using namespace std;
void pcm_to_wav(const char* pcm_filename, const char* wav_filename, int sample_rate, int bits_per_sample, int channels)
{
// 打开PCM文件
ifstream pcm_file(pcm_filename, ios::binary);
if (!pcm_file.is_open())
{
cerr << "Can't open PCM file: " << pcm_filename << endl;
return;
}
// 打开WAV文件
ofstream wav_file(wav_filename, ios::binary);
if (!wav_file.is_open())
{
cerr << "Can't create WAV file: " << wav_filename << endl;
return;
}
// 计算数据长度和文件长度
pcm_file.seekg(0, ios::end);
uint32_t data_size = pcm_file.tellg();
uint32_t file_size = 36 + data_size;
// 设置WAV文件头
wav_file.write("RIFF", 4);
wav_file.write((char*)&file_size, 4);
wav_file.write("WAVE", 4);
wav_file.write("fmt ", 4);
uint32_t fmt_size = 16;
wav_file.write((char*)&fmt_size, 4);
uint16_t audio_format = 1;
wav_file.write((char*)&audio_format, 2);
wav_file.write((char*)&channels, 2);
wav_file.write((char*)&sample_rate, 4);
uint32_t byte_rate = sample_rate * channels * bits_per_sample / 8;
wav_file.write((char*)&byte_rate, 4);
uint16_t block_align = channels * bits_per_sample / 8;
wav_file.write((char*)&block_align, 2);
wav_file.write((char*)&bits_per_sample, 2);
wav_file.write("data", 4);
wav_file.write((char*)&data_size, 4);
// 将PCM数据写入WAV文件
pcm_file.seekg(0, ios::beg);
char* buffer = new char[4096];
while (!pcm_file.eof())
{
pcm_file.read(buffer, 4096);
wav_file.write(buffer, pcm_file.gcount());
}
delete[] buffer;
// 关闭文件
pcm_file.close();
wav_file.close();
}
int main()
{
pcm_to_wav("audio.pcm", "audio.wav", 44100, 16, 2);
return 0;
}
```
该代码将PCM文件“audio.pcm”转换为WAV文件“audio.wav”,采样率为44100Hz,每个样本16位,2个声道。你可以根据自己的需要修改这些参数。
阅读全文