title: Play audio from a stream using C#
body: <p>Is there a way in C# to play audio (for example, MP3) direcly from a <a href="http://msdn.microsoft.com/en-us/library/system.io.stream%28v=vs.110%29.aspx" rel="nofollow noreferrer">System.IO.Stream</a> that for instance was returend from a WebRequest without saving the data temporarily to the disk?</p>
  
  <hr>
  
  <h3>Solution with <a href="https://github.com/naudio/NAudio" rel="nofollow noreferrer">NAudio</a></h3>
  
  <p>With the help of <a href="https://github.com/naudio/NAudio" rel="nofollow noreferrer">NAudio</a> 1.3 it is possible to:</p>
  
  <ol>
  <li>Load an MP3 file from a URL into a MemoryStream</li>
  <li>Convert MP3 data into wave data after it was completely loaded</li>
  <li>Playback the wave data using <a href="https://github.com/naudio/NAudio" rel="nofollow noreferrer">NAudio</a>'s WaveOut class</li>
  </ol>
  
  <p>It would have been nice to be able to even play a half loaded MP3 file, but this seems to be impossible due to the <a href="https://github.com/naudio/NAudio" rel="nofollow noreferrer">NAudio</a> library design.</p>
  
  <p>And this is the function that will do the work:</p>
  
  <pre><code>    public static void PlayMp3FromUrl(string url)
      {
          using (Stream ms = new MemoryStream())
          {
              using (Stream stream = WebRequest.Create(url)
                  .GetResponse().GetResponseStream())
              {
                  byte[] buffer = new byte[32768];
                  int read;
                  while ((read = stream.Read(buffer, 0, buffer.Length)) &gt; 0)
                  {
                      ms.Write(buffer, 0, read);
                  }
              }
  
              ms.Position = 0;
              using (WaveStream blockAlignedStream =
                  new BlockAlignReductionStream(
                      WaveFormatConversionStream.CreatePcmStream(
                          new Mp3FileReader(ms))))
              {
                  using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                  {
                      waveOut.Init(blockAlignedStream);
                      waveOut.Play();                        
                      while (waveOut.PlaybackState == PlaybackState.Playing )                        
                      {
                          System.Threading.Thread.Sleep(100);
                      }
                  }
              }
          }
      }
  </code></pre>