c++ pcm二进制数据转wav代码
时间: 2023-07-28 18:06:24 浏览: 117
pcm转换成wav
5星 · 资源好评率100%
下面是一个简单的C++代码示例,用于将PCM二进制数据转换为WAV文件:
```c++
#include <fstream>
#include <iostream>
#include <cstring>
#include <stdint.h>
using namespace std;
int main(int argc, char* argv[]) {
// 检查输入参数
if (argc != 4) {
cout << "Usage: " << argv[0] << " <input file> <output file> <sample rate>" << endl;
return 1;
}
// 打开输入文件
ifstream input(argv[1], ios::binary);
if (!input) {
cout << "Failed to open input file: " << argv[1] << endl;
return 1;
}
// 创建输出文件
ofstream output(argv[2], ios::binary);
if (!output) {
cout << "Failed to create output file: " << argv[2] << endl;
return 1;
}
// 设置采样率
int sampleRate = atoi(argv[3]);
int bitsPerSample = 16;
int channels = 1;
// 写入WAV文件头
char header[44];
memset(header, 0, sizeof(header));
memcpy(header, "RIFF", 4);
uint32_t fileSize = 0;
memcpy(header + 4, &fileSize, 4);
memcpy(header + 8, "WAVE", 4);
memcpy(header + 12, "fmt ", 4);
uint32_t fmtSize = 16;
memcpy(header + 16, &fmtSize, 4);
uint16_t audioFormat = 1;
memcpy(header + 20, &audioFormat, 2);
uint16_t numChannels = channels;
memcpy(header + 22, &numChannels, 2);
uint32_t sampleRateHz = sampleRate;
memcpy(header + 24, &sampleRateHz, 4);
uint32_t byteRate = sampleRateHz * numChannels * bitsPerSample / 8;
memcpy(header + 28, &byteRate, 4);
uint16_t blockAlign = numChannels * bitsPerSample / 8;
memcpy(header + 32, &blockAlign, 2);
memcpy(header + 34, &bitsPerSample, 2);
memcpy(header + 36, "data", 4);
uint32_t dataSize = 0;
memcpy(header + 40, &dataSize, 4);
output.write(header, sizeof(header));
// 逐个读取PCM样本并将其写入WAV文件
char buffer[4096];
while (input) {
int bytes = input.read(buffer, sizeof(buffer)).gcount();
if (bytes > 0) {
output.write(buffer, bytes);
fileSize += bytes;
}
}
// 更新WAV文件头
dataSize = fileSize - sizeof(header);
memcpy(header + 4, &fileSize, 4);
memcpy(header + 40, &dataSize, 4);
output.seekp(0);
output.write(header, sizeof(header));
// 关闭文件并退出
input.close();
output.close();
cout << "Conversion completed" << endl;
return 0;
}
```
在上面的代码中,我们首先检查输入参数,然后打开输入文件。接下来,我们创建输出文件,并设置WAV文件的采样率、位深度和通道数。我们使用这些参数填写WAV文件头,并将其写入输出文件。然后,我们逐个读取输入文件中的PCM样本,并将它们写入输出文件。最后,我们更新WAV文件头中的数据大小字段,并关闭文件。
请注意,上述代码只能用于单通道、16位深度的PCM数据,如果您需要处理其他类型的PCM数据,需要相应地修改代码。
阅读全文