PCM声音数据保存成WAV格式音频

解码音频之后如果播放出现问题,首先需要知道解码的音频是不是正确,然后再看播放是否有问题。看解码的音频是否正确可以将PCM声音数据保存成WAV格式音频,用其他播放器播放看是否正确。

namespace {
	FILE *pFile = NULL;
	int g_nData = 0;

	typedef char      s8;    //有符号8位整数
	typedef short     s16;   //有符号16位整数
	typedef int       s32;   //有符号32位整数
	struct WAVE_TAG
	{
		s8     riff[4];            //"RIFF",资源交换文件标志
		s32    fsize;              //文件大小(从下个地址开始到文件尾的总字节数)
		s8     wave[4];            //"WAVE",文件标志
	};
	struct WAVE_FMT
	{
		s8     fmt[4];             //"fmt ",波形格式标志 
		s32    chunsize;           //文件内部格式信息大小
		s16    wformattag;         //音频数据编码方式 1PCM
		s16    wchanles;           //声道数 1,2
		s32    dwsamplespersec;    //采样率 441000
		s32    dwavgbytespersec;   //波形数据传输速率(每秒平均字节数)
		s16    wblockalign;        //数据的调整数(按字节计算)
		s16    wbitspersample;     //样本数据位数
	};
	struct WAVE_DAT
	{
		s8     data[4];            //"data",数据标志符
		s32    datasize;           //采样数据总长度 
	};
	struct WAVE_HEAD
	{
		WAVE_TAG   WaveTag; 
		WAVE_FMT   WaveFmt;
		WAVE_DAT   WaveDat;
	}wavhead;
}


//初始化
pFile = fopen("e:\\test1.wav", "wb");

wavhead.WaveTag.riff[0] = 'R';
wavhead.WaveTag.riff[1] = 'I';
wavhead.WaveTag.riff[2] = 'F';
wavhead.WaveTag.riff[3] = 'F';

wavhead.WaveTag.wave[0] = 'W';
wavhead.WaveTag.wave[1] = 'A';
wavhead.WaveTag.wave[2] = 'V';
wavhead.WaveTag.wave[3] = 'E';

wavhead.WaveFmt.fmt[0] = 'f';
wavhead.WaveFmt.fmt[1] = 'm';
wavhead.WaveFmt.fmt[2] = 't';
wavhead.WaveFmt.fmt[3] = ' ';
wavhead.WaveFmt.chunsize = sizeof(PCMWAVEFORMAT);
wavhead.WaveFmt.wformattag = WAVE_FORMAT_PCM;

wavhead.WaveFmt.wchanles = 2; // 音频通道
wavhead.WaveFmt.dwsamplespersec = 48000; // 采样率
wavhead.WaveFmt.dwavgbytespersec = wavhead.WaveFmt.dwsamplespersec * wavhead.WaveFmt.wchanles * 2;   //波形数据传输速率(每秒平均字节数)
wavhead.WaveFmt.wblockalign = 8;      
wavhead.WaveFmt.wbitspersample = 32;    

wavhead.WaveDat.data[0] = 'd';
wavhead.WaveDat.data[1] = 'a';
wavhead.WaveDat.data[2] = 't';
wavhead.WaveDat.data[3] = 'a';

g_nData = 0;
fseek(pFile, sizeof(wavhead), SEEK_SET); // 留出文件头位置


// 写入数据
fwrite(pPCMData, nPCMSize, 1, pFile);
g_nData += nPCMSize;


// 写入文件头并保存
if (pFile != NULL) {
	fseek(pFile, 0, SEEK_SET);
	wavhead.WaveDat.datasize = g_nData;
	wavhead.WaveTag.fsize = (g_nData + sizeof(wavhead));
	fwrite(&wavhead, sizeof(wavhead), 1, pFile);
	fclose(pFile);
	pFile = NULL;
}

 

你可能感兴趣的:(PCM声音数据保存成WAV格式音频)