This project has moved and is read-only. For the latest updates, please go here.

Playing an infinite length stream

Jul 9, 2009 at 8:44 PM

I'm looking into using naudio to play an RTP stream. It looks as though the correct way to approach this is to derive from WaveStream and override the Read() call. That makes sense, but I have questions about other possible overrides in that class. Do I need to override Length, Position and HasData ( or any other ) methods? If so, what makes sense to return for them?

I'm most concerned about latency. Assuming I don't want to require ASIO, would the DirectSoundOut give me the lowest latency?

One more issue - I'm writing a WPF app but a few of the classes ( like DirectSoundOut ) require passing in a System.Windows.Forms to the constructor and I don't have one available. Is it ok to pass null for this argument?

Jul 10, 2009 at 6:24 PM

Here's some code I tried to use to get started. In theory this code was supposed to play random noise out the sound card. I don't get any errors and the Read() method is being called on my TestStream but nothing comes out of the sound card. Since I'm using WPF I'm just creating a Form to pass into the DirectSoundOut constructor - no idea if that should work.

 

  class TestStream : NAudio.Wave.WaveStream
  {
    NAudio.Wave.WaveFormat _Format = new NAudio.Wave.WaveFormat();
    public override NAudio.Wave.WaveFormat WaveFormat
    {
      get
      {
        return _Format;
      }
    }
    public override long Length
    {
      get { return long.MaxValue / 32; }
    }
    long _Position;
    public override long Position
    {
      get { return _Position; }
      set { }
    }
    public override bool CanSeek
    {
      get { return false; }
    }
    public override bool HasData(int count)
    {
      return true;
    }

    Random _Rand = new Random();
    public override int Read(byte[] buffer, int offset, int count)
    {
      _Rand.NextBytes(buffer);
      _Position += count;
      return count;
    }
  }


// and here's where I start the play

    System.Windows.Forms.Form f = new System.Windows.Forms.Form();
    TestStream _Stream;
    NAudio.Wave.DirectSoundOut _Dso;
    protected override void OnInitialized(EventArgs e)
    {
      base.OnInitialized(e);
      try
      {
        _Stream = new TestStream();
        _Dso = new NAudio.Wave.DirectSoundOut(f, 1000);
        _Dso.Init(_Stream);
        _Dso.Play();
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }