Play audio from a stream using C#
Edit: Answer updated to reflect changes in recent versions of NAudio
It's possible using the NAudio open source .NET audio library I have written. It looks for an ACM codec on your PC to do the conversion. The Mp3FileReader supplied with NAudio currently expects to be able to reposition within the source stream (it builds an index of MP3 frames up front), so it is not appropriate for streaming over the network. However, you can still use the MP3Frame
and AcmMp3FrameDecompressor
classes in NAudio to decompress streamed MP3 on the fly.
I have posted an article on my blog explaining how to play back an MP3 stream using NAudio. Essentially you have one thread downloading MP3 frames, decompressing them and storing them in a BufferedWaveProvider
. Another thread then plays back using the BufferedWaveProvider
as an input.
The SoundPlayer class can do this. It looks like all you have to do is set its Stream property to the stream, then call Play
.
edit
I don't think it can play MP3 files though; it seems limited to .wav. I'm not certain if there's anything in the framework that can play an MP3 file directly. Everything I find about that involves either using a WMP control or interacting with DirectX.
Bass can do just this. Play from Byte[] in memory or a through file delegates where you return the data, so with that you can play as soon as you have enough data to start the playback..