title: Prepending WAV header to audio data of 16-bit unsigned integers
body: <p>I am receiving an audio clip in form of 16-bit unsigned integers. I'd like to prepend a WAV header and save it into a file. I used <a href="http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html" rel="nofollow noreferrer">this</a> as my reference to hard code the header. (well, those parts that are fixed)</p>
  
  <p>Here is my code for constructing the WAVE header:</p>
  
  <pre><code>std::string getWaveHeader(int data_size_bits, int channels, int sample_rate) {
      char header[] = 
      "RIFF"  // Chunk ID
      "\x00\x00\x00\x00"  // Chunk size (not set)
      "WAVE"  // WAVE ID
      "fmt "  // Chunk ID
      "\x28\x00\x00\x00" // [little-endian] WAVE header size (40)
      "\xfe\xff"  // [little-endian] WAVE format code: WAVE_FORMAT_EXTENSIBLE
      "\x00\x00"  // number of channels (not set)
      "\x00\x00\x00\x00"  // sample rate (not set)
      "\x00\x00\x00\x00"  // average bytes/sec (not set)
      "\x00\x00"  // block size (not set)
      "\x00\x00"  // bits per sample (not set)
      "\x16\x00"  // [little-endian] size of extension (22)
      "\x00\x00"  // valid bits (not set)
      "\x00\x00\x00\x00"  // speaker position mask (not set)
      "\x03\x00\x00\x00"   // WAV_HEADER_SUB_FORMAT_CODE
      "\x00\x00\x10\x00"   // WAV_HEADER_SUB_GUID
      "\x80\x00\x00\xaa"   // WAV_HEADER_SUB_GUID
      "\x00\x38\x9b\x71"   // WAV_HEADER_SUB_GUID
      "fact"  // Chunk ID
      "\x04\x00"  // [little-endian] Chunk size (4)
      "\x00\x00\x00\x00"  // dwSample Length (not set)
      "data"  // Chunk ID
      "\x00\x00\x00\x00";  // Wav header size (not set)
  
      // modifications on |header| ....
      // ...
      // Set the following params in little-endian using given information.
      // 1. Chunk size: |data_size_bits| + |header_size_bits| - 8
      // 2. number of channels (given)
      // 3. sample rate (given)
      // 4. average bytes/sec: |sample rate| * |bit_per_sample|/8 * |channels|
      // 5. block size: |bit_per_sample|/8 * |channels|
      // 6. bits per sample (given)
      // 7. valid bits: |bit_per_sample|
      // 8. Wav header size: |data_size_bits|
  
      std::string header_str = ConvertToString(header);
  
      return header_str;
  }
  </code></pre>
  
  <p>I prepend the header to the byte array I receive and save it into a file. The saved output file doesn't seem to have all the right meta info in its header and I was wondering if I'm using the right header and parameters for my case.</p>
  
  <p>My reference: <a href="http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html" rel="nofollow noreferrer">http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html</a></p>