How to play MP3 file using NAudio

WaveStream waveStream = new Mp3FileReader(mp3FileToPlay); var waveOut = new WaveOut(); waveOut.Init(waveStream); waveOut.Play(); 

This throws an exception:

WaveBadFormat call waveOutOpen

The encoding type is "MpegLayer3" like NAudio.

How can I play mp3 file using NAudio?

+7
c # mp3 naudio
source share
2 answers

Try it 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); } } } } 

Change this code is deprecated (applies to NAudio 1.3). Not recommended in new versions of NAudio. See Alternative Answer.

+7
source share

For users of NAudio 1.6 and above, please do not use the code in the original accepted answer. You do not need to add a WaveFormatConversionStream or BlockAlignReductionStream , and you should avoid using WaveOut with function WaveOutEvent ( WaveOutEvent preferred if you are not in a WinForms or WPF application). In addition, if you do not want to block playback, you usually will not sleep until the sound ends. Just sign up for the WaveOut PlaybackStopped event.

The following code will work very well to play MP3 in NAudio:

 reader = new Mp3FileReader("test.mp3"); var waveOut = new WaveOut(); // or WaveOutEvent() waveOut.Init(reader); waveOut.Play(); 
+28
source share

All Articles