title: NAudio playing a sine wave for x milliseconds using C#
body: <p>I am using <a href="https://naudio.codeplex.com/" rel="noreferrer">NAudio</a> to play a sinewave of a given frequency as in the blog post <em><a href="http://mark-dot-net.blogspot.com/2009/10/playback-of-sine-wave-in-naudio.html" rel="noreferrer">Playback of Sine Wave in NAudio</a></em>. I just want the sound to play() for x milliseconds and then stop.</p>
  
  <p>I tried a thread.sleep, but the sound stops straightaway. I tried a timer, but when the WaveOut is disposed there is a cross-thread exception.</p>
  
  <p>I tried this code, but when I call beep the program freezes.</p>
  
  <pre><code>public class Beep
  {
      public Beep(int freq, int ms)
      {
          SineWaveProvider32 sineWaveProvider = new SineWaveProvider32();
          sineWaveProvider.Amplitude = 0.25f;
          sineWaveProvider.Frequency = freq;
  
          NAudio.Wave.WaveOut waveOut = new NAudio.Wave.WaveOut(WaveCallbackInfo.FunctionCallback());
          waveOut.Init(sineWaveProvider);
          waveOut.Play();
          Thread.Sleep(ms);
          waveOut.Stop();
          waveOut.Dispose();
      }
  }
  
  public class SineWaveProvider32 : NAudio.Wave.WaveProvider32
  {
      int sample;
  
      public SineWaveProvider32()
      {
          Frequency = 1000;
          Amplitude = 0.25f; // Let's not hurt our ears
      }
  
      public float Frequency { get; set; }
      public float Amplitude { get; set; }
  
      public override int Read(float[] buffer, int offset, int sampleCount)
      {
          int sampleRate = WaveFormat.SampleRate;
          for (int n = 0; n &lt; sampleCount; n++)
          {
              buffer[n + offset] = (float)(Amplitude * Math.Sin((2 * Math.PI * sample * Frequency) / sampleRate));
              sample++;
              if (sample &gt;= sampleRate)
                  sample = 0;
          }
     }
  </code></pre>