wav音频文件格式解析

时间:2021-10-27 16:08:55
wav是微软开发的一种音频文件格式,注意,wav文件格式是无损音频文件格式,相对于其他音频格式文件数据是没有经过压缩的,通常文件也相对比较大些。

文件格式如图所示:

wav音频文件格式解析

解析代码如下:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

struct WAV_Format {
	uint32_t ChunkID;	/* "RIFF" */
	uint32_t ChunkSize;	/* 36 + Subchunk2Size */
	uint32_t Format;	/* "WAVE" */

	/* sub-chunk "fmt" */
	uint32_t Subchunk1ID;	/* "fmt " */
	uint32_t Subchunk1Size;	/* 16 for PCM */
	uint16_t AudioFormat;	/* PCM = 1*/
	uint16_t NumChannels;	/* Mono = 1, Stereo = 2, etc. */
	uint32_t SampleRate;	/* 8000, 44100, etc. */
	uint32_t ByteRate;	/* = SampleRate * NumChannels * BitsPerSample/8 */
	uint16_t BlockAlign;	/* = NumChannels * BitsPerSample/8 */	
	uint16_t BitsPerSample;	/* 8bits, 16bits, etc. */

	/* sub-chunk "data" */
	uint32_t Subchunk2ID;	/* "data" */
	uint32_t Subchunk2Size;	/* data size */
}; 

int main(void)
{
	FILE *fp = NULL;
	struct WAV_Format wav;

	fp = fopen("test.wav", "rb");
	if (!fp) {
		printf("can't open audio file\n");
		exit(1);
	}

	fread(&wav, 1, sizeof(struct WAV_Format), fp);

	printf("ChunkID \t%x\n", wav.ChunkID);
	printf("ChunkSize \t%d\n", wav.ChunkSize);
	printf("Format \t\t%x\n", wav.Format);
	printf("Subchunk1ID \t%x\n", wav.Subchunk1ID);
	printf("Subchunk1Size \t%d\n", wav.Subchunk1Size);
	printf("AudioFormat \t%d\n", wav.AudioFormat);
	printf("NumChannels \t%d\n", wav.NumChannels);
	printf("SampleRate \t%d\n", wav.SampleRate);
	printf("ByteRate \t%d\n", wav.ByteRate);
	printf("BlockAlign \t%d\n", wav.BlockAlign);
	printf("BitsPerSample \t%d\n", wav.BitsPerSample);
	printf("Subchunk2ID \t%x\n", wav.Subchunk2ID);
	printf("Subchunk2Size \t%d\n", wav.Subchunk2Size);

	fclose(fp);

	return 0;
}

// 2016-09-22 add
ByteRate计算方法是SampleRate * NumChannels * BitsPerSample/8,那么这个公式计算出来的是1秒钟音频数据大小,单位为Byte,以44100、16bit、2通道为例,那么计算出来值为176400,根据总音频数据大小,可以得出播放时间的计算公式为Subchunk2Size / ByteRate。


参考:http://soundfile.sapp.org/doc/WaveFormat/