How to Write a WAV File in c++

March 21, 2013 General News 12 Comments

It's surprisingly hard to find clean and simple code to do this, but it's surprisingly easy to do. Here it is, if anyone has ever wanted to write their own sound files in c++.

My code formatting in this blog is horrible, hence linking it as a separate file. Now all you do is call writeWAVData like this:

writeWAVData("mySound.wav", mySampleBuffer, mySampleBufferSize, 44100, 1);

Which would write a 44.1khz mono wav ("CD quality"). mySampleBuffer should be an array of signed shorts for 16-bit sound, floats for 32-bit, unsigned chars for 8-bit. Since the function is templatized, it automatically detects the format and takes care of the relevant fields in the WAV header.

Oh, and this only works on a little-endian machine, since WAV is expected to be little...but that probably doesn't matter to anyone these days, right?

Enjoy...I guess?