WaveStream waveStream = new Mp3FileReader(mp3FileToPlay);
var waveOut = new WaveOut();
waveOut.Init(waveStream);
waveOut.Play();
This throws an exception:
WaveBadFormat calling waveOutOpen
The encoding type is "MpegLayer3" as NAudio.
How can I play a mp3 file with NAudio?
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With