Skip to content

Instantly share code, notes, and snippets.

@schellingb
Last active December 2, 2023 15:06
Show Gist options
  • Save schellingb/b3c3b1216e309c9f1a1648f4b7ee39ea to your computer and use it in GitHub Desktop.
Save schellingb/b3c3b1216e309c9f1a1648f4b7ee39ea to your computer and use it in GitHub Desktop.
Generate WAV header
Bit8u hdr[44];
#define WAV_WRITE_LE16(b,v) { (b)[0] = (unsigned char)((unsigned short)(v) & 0xFF); (b)[1] = (unsigned char)((unsigned short)(v) >> 8); }
#define WAV_WRITE_LE32(b,v) { (b)[0] = (unsigned char)((unsigned int)(v) & 0xFF); (b)[1] = (unsigned char)(((unsigned int)(v) >> 8) & 0xFF); (b)[2] = (unsigned char)(((unsigned int)(v) >> 16) & 0xFF); (b)[3] = (unsigned char)((unsigned int)(v) >> 24); }
WAV_WRITE_LE32(hdr + 0, 0x46464952U); //"RIFF"
WAV_WRITE_LE32(hdr + 4, 36 + pcm_data_size); //chunk size
WAV_WRITE_LE32(hdr + 8, 0x45564157U); //"WAVE"
WAV_WRITE_LE32(hdr + 12, 0x20746d66U); //subchunk 1 id "fmt "
WAV_WRITE_LE32(hdr + 16, 16); //subchunk 1 size
WAV_WRITE_LE16(hdr + 20, 1); //audio format
WAV_WRITE_LE16(hdr + 22, channels); //num of chan
WAV_WRITE_LE32(hdr + 24, sample_rate); //samples per sec
WAV_WRITE_LE32(hdr + 28, sample_rate * channels * sizeof(short)); //bytes per sec
WAV_WRITE_LE16(hdr + 32, channels * sizeof(short)); //block align
WAV_WRITE_LE16(hdr + 34, sizeof(short) * 8); //bits per sample
WAV_WRITE_LE32(hdr + 36, 0x61746164U); //subchunk 2 id "data"
WAV_WRITE_LE32(hdr + 40, pcm_data_size); //subchunk 2 size
#undef WAV_WRITE_LE16
#undef WAV_WRITE_LE32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment