How to Write a WAV File in c++

It is 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're all running little endian...


7 thoughts on “How to Write a WAV File in c++”

  1. Hi,
    can I use the example in project licensed unsed Apache License v 2.0? Can you please give it such license?



  2. Josh !!

    I was just on the hunt for some nice WAV writing code and BOOM - the one and only JP of LT brings the goods ;-)

    Suuper nice template man, I'm using it in Jen :-) Just thought I'd point out that, the PCM format tag ("1") does not support floats and will cause dodgy / heavily distorted playback if "mySampleBuffer" is an array of floats. There should be a condition to write "3" (aka WAVE_FORMAT_IEEE_FLOAT) to the format tag if sampleType is a float.

    if(std::tr1::is_floating_point::value) write(stream, 3);
    else write(stream,1);

    just in case anyone else checking this out is hoping to write 32-bit :-)

    Anyways, cheers for the nice neat snippet!

    1. Ha epic coincidence! Thanks for the info on floats - good to know in case it comes up down the road :) Amended the code as per your suggestion.

      Cheers and happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>