How to play a MP3 file using NAudio
Try like this:
class Program
{
static void Main()
{
using (var ms = File.OpenRead("test.mp3"))
using (var rdr = new Mp3FileReader(ms))
using (var wavStream = WaveFormatConversionStream.CreatePcmStream(rdr))
using (var baStream = new BlockAlignReductionStream(wavStream))
using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
{
waveOut.Init(baStream);
waveOut.Play();
while (waveOut.PlaybackState == PlaybackState.Playing)
{
Thread.Sleep(100);
}
}
}
}
Edit this code is now out of date (relates to NAudio 1.3). Not recommended on newer versions of NAudio. Please see alternative answer.
For users of NAudio 1.6 and above, please do not use the code in the original accepted answer. You don't need to add a WaveFormatConversionStream
, or a BlockAlignReductionStream
, and you should avoid using WaveOut
with function callbacks (WaveOutEvent
is preferable if you are not in a WinForms or WPF application). Also, unless you want blocking playback, you would not normally sleep until audio finishes. Just subscribe to WaveOut
's PlaybackStopped
event.
The following code will work just fine to play an MP3 in NAudio:
var reader = new Mp3FileReader("test.mp3");
var waveOut = new WaveOut(); // or WaveOutEvent()
waveOut.Init(reader);
waveOut.Play();