版权声明:版权声明:尊重博主原创文章,转载请注明出处 https://blog.csdn.net/a568478312/article/details/78196285
pcm是原始音频数据,wav是windows中常见的音频格式,只是在pcm数据中添加了一个文件头,wav文件格式可以参考http://soundfile.sapp.org/doc/WaveFormat/
// WAVWriter.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
typedef struct WAVE_HEADER {
//RIFF
char chunkID[4];
//long int 4字节 某个大小
unsigned long chunkSize;
//WAVE
char formate[4];
};
typedef struct WAVE_FMT {
//fmt 注意最后有个空格
char subchunk1ID[4];
unsigned long subchunk1Size;
unsigned short audioFormatTag;
unsigned short numChannels;
unsigned long sampleRate;
unsigned long byteRate;
unsigned short blockAlign;
unsigned short bitPerSample;
};
typedef struct WAVE_DATA {
char subchunk2Id[4];
unsigned long subchunk2Size;
};
long getFileSize(char* filename) {
FILE *fp = fopen(filename, "r");
if (!fp) return -1;
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fclose(fp);
return size;
}
int converToWAV(const char *pcmpath, int channels, int sample_rate, const char *wavepath) {
int bits = 16;
WAVE_HEADER pcmHEADER;
WAVE_FMT pcmFMT;
WAVE_DATA pcmDATA;
FILE *fp, *fpout;
fp = fopen(pcmpath, "rb");
if (NULL == fp) {
std::cout << "file open failed" << endl;
return -1;
}
long pcmSize = getFileSize((char*)pcmpath);
//WAVE_HEADER
memcpy(pcmHEADER.chunkID, "RIFF", strlen("RIFF"));
pcmHEADER.chunkSize = 36 + pcmSize;
memcpy(pcmHEADER.formate, "WAVE", strlen("WAVE"));
fpout = fopen(wavepath, "wb");
if (NULL == fpout) {
cout << "file open failed" << endl;
return -1;
}
fwrite(&pcmHEADER, sizeof(pcmHEADER), 1, fpout);
//WAVE_FMT
pcmFMT.numChannels = channels;
pcmFMT.sampleRate = sample_rate;
pcmFMT.bitPerSample = bits;
pcmFMT.byteRate = sample_rate*channels *pcmFMT.bitPerSample / 8;
memcpy(pcmFMT.subchunk1ID, "fmt ", strlen("fmt "));
pcmFMT.subchunk1Size = 16;
pcmFMT.audioFormatTag = 1;
pcmFMT.blockAlign = channels*pcmFMT.bitPerSample / 8;
fwrite(&pcmFMT, sizeof(pcmFMT), 1, fpout);
//WAVE_DATA
memcpy(pcmDATA.subchunk2Id, "data", strlen("data"));
pcmDATA.subchunk2Size = pcmSize;
fwrite(&pcmDATA, sizeof(pcmDATA), 1, fpout);
char *buff=(char*)malloc(512);
int len;
while ((len = fread(buff, sizeof(char), 512, fp)) != 0)
{
fwrite(buff, sizeof(char), len, fpout);
}
free(buff);
fclose(fp);
fclose(fpout);
}
int main()
{
converToWAV("input.pcm", 1, 44100, "output.wav");
return 0;
}
完全参考格式来书写的,pcm数据注意采样率和通道数。