How to encapsulate pcm data into wav Files in C Language
Pcm is the raw audio data. wav is a common audio format in windows. It only adds a file header to the pcm data.
// WAVWriter. cpp: defines the entry point of the console application. // # Include "stdafx. h" # include
Using namespace std; typedef struct WAVE_HEADER {// RIFF char chunkID [4]; // long int 4-byte unsigned long chunkSize; // WAVE char formate [4];}; typedef struct WAVE_FMT {// fmt note that there is a space char character [4]; unsigned long character; unsigned short audioFormatTag; unsigned short numChannels; unsigned long sampleRate; unsigned long byteRate; unsigned short blockAlign; unsigned short bitPerSample;}; t Ypedef 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 (cha R *) 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. bit PerSample = 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 ;}
For more information, see the format. Note the sampling rate and number of channels for pcm data.