title: How to add playable(such as wav,wmv) header with PCM data/buffer in iOS?
body: <p>I am trying to add a wav header on top of raw PCM data to make it playable via AVAudioPlayer. But i couldn't find any solution or source code to do that on iOS using Objective-C/Swift. Though i found <a href="https://stackoverflow.com/questions/24772844/convert-a-pcm-float-buffer-to-a-wav-nsdata">this</a> but it doesn't have correct answer.</p>
  
  <p>But i found a piece of code <a href="http://www.pceworld.com/view/19897879" rel="nofollow noreferrer">here</a> which is in C and also contains some issue. The wav file doesn't play properly which is generated from that code. </p>
  
  <p>I have given my codes below which i have coded so far.</p>
  
  <pre><code>int NumChannels = AUDIO_CHANNELS_PER_FRAME;
  short BitsPerSample = AUDIO_BITS_PER_CHANNEL;
  int SamplingRate = AUDIO_SAMPLE_RATE;
  int numOfSamples = [[NSData dataWithContentsOfFile:filePath] length];
  
  int ByteRate = NumChannels*BitsPerSample*SamplingRate/8;
  short BlockAlign = NumChannels*BitsPerSample/8;
  int DataSize = NumChannels*numOfSamples*BitsPerSample/8;
  int chunkSize = 16;
  int totalSize = 36 + DataSize;
  short audioFormat = 1;
  
  if((fout = fopen([wavFilePath cStringUsingEncoding:1], "w")) == NULL)
  {
      printf("Error opening out file ");
  }
  
  fwrite("RIFF", sizeof(char), 4,fout);
  fwrite(&amp;totalSize, sizeof(int), 1, fout);
  fwrite("WAVE", sizeof(char), 4, fout);
  fwrite("fmt ", sizeof(char), 3, fout);
  fwrite(&amp;chunkSize, sizeof(int),1,fout);
  fwrite(&amp;audioFormat, sizeof(short), 1, fout);
  fwrite(&amp;NumChannels, sizeof(short),1,fout);
  fwrite(&amp;SamplingRate, sizeof(int), 1, fout);
  fwrite(&amp;ByteRate, sizeof(int), 1, fout);
  fwrite(&amp;BlockAlign, sizeof(short), 1, fout);
  fwrite(&amp;BitsPerSample, sizeof(short), 1, fout);
  fwrite("data", sizeof(char), 3, fout);
  fwrite(&amp;DataSize, sizeof(int), 1, fout);
  </code></pre>
  
  <p>The file is playing too fast, the sound is distorted and only first 10 to 20(around) seconds are playing. I think, the wav header isn't generating correctly(Because i am able to play same PCM data/buffer using AudioUnit/AudioQueue).  So what i am missing in my code ? Any help would be highly appreciated.</p>
  
  <p>Thanks in advance.</p>