title: Creating a .wav File in C#
body: <p>As an excuse to learn C#, I have been trying to code a simple project: creating audio files. To start, I want to make sure that I can write files that meet the WAVE format. I have researched the format online (for example, <a href="https://ccrma.stanford.edu/courses/422/projects/WaveFormat/">here</a>), but whenever I try to play back a file, it won't open correctly. Here is my code. Is something missing or incorrect?</p>
  
  <pre><code>uint numsamples = 44100;
  ushort numchannels = 1;
  ushort samplelength = 1; // in bytes
  uint samplerate = 22050;
  
  FileStream f = new FileStream("a.wav", FileMode.Create);
  BinaryWriter wr = new BinaryWriter(f);
  
  wr.Write("RIFF");
  wr.Write(36 + numsamples * numchannels * samplelength);
  wr.Write("WAVEfmt ");
  wr.Write(16);
  wr.Write((ushort)1);
  wr.Write(numchannels);
  wr.Write(samplerate);
  wr.Write(samplerate * samplelength * numchannels);
  wr.Write(samplelength * numchannels);
  wr.Write((ushort)(8 * samplelength));
  wr.Write("data");
  wr.Write(numsamples * samplelength);
  
  // for now, just a square wave
  Waveform a = new Waveform(440, 50);
  
  double t = 0.0;
  for (int i = 0; i &lt; numsamples; i++, t += 1.0 / samplerate)
  {
      wr.Write((byte)((a.sample(t) + (samplelength == 1 ? 128 : 0)) &amp; 0xff));
  }
  </code></pre>