Is there a way in C# to play audio (e.g. MP3) direcly from a Stream (I mean the real .NET class) that for instance was returend from a WebRequest without saving the data temporarily to the disk?
Solution with NAudio
With the help of NAudio 1.3 it is possible to:
- load a mp3 file from a url into a MemoryStream
- convert mp3 data into wave data after it was completely loaded
- playback the wave data using the NAudios WaveOut class
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 NAudio library design.
And this is the function that will do the work:
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)) > 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);
}
}
}
}
}