my preferred way to play any MP3 files with NAudio is this. I prefer to block the playing thread until Playback stopped with event listeners. Also, for the best compatibility, I use MP3Sharp to load the MP3 file and then pass it to NAudio since NAudio did not come with MP3 codecs.
using System;
using NAudio.Wave;
using System.Threading;
using MP3Sharp;
using System.IO;
namespace jessielesbian.NAudioTest
{
public static class Program
{
static void Main(string[] args)
{
Console.WriteLine("loading and parsing MP3 file...");
MP3Stream stream = new MP3Stream("c:\workspaces\Stunning! Boeing s 737 MAX on Flying Display.mp3");
WaveFormat waveFormat = new WaveFormat(stream.Frequency, stream.ChannelCount);
Console.WriteLine("allocating playback cache...");
FastWaveBuffer fastWaveBuffer = new FastWaveBuffer(waveFormat, (int) stream.Length);
Console.WriteLine("populating playback cache...");
stream.CopyTo(fastWaveBuffer);
fastWaveBuffer.Seek(0, SeekOrigin.Begin);
Console.WriteLine("unloading MP3 file...");
stream.Dispose();
Console.WriteLine("prepairing player...");
WaveOutEvent waveOutEvent = new WaveOutEvent();
waveOutEvent.Init(fastWaveBuffer);
waveOutEvent.Volume = 1;
Console.WriteLine("arming ManualResetEvent...");
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
waveOutEvent.PlaybackStopped += (object sender, StoppedEventArgs e) => {
manualResetEvent.Set();
};
Console.WriteLine("done!");
waveOutEvent.Play();
manualResetEvent.WaitOne();
}
}
public sealed class FastWaveBuffer : MemoryStream, IWaveProvider
{
public FastWaveBuffer(WaveFormat waveFormat, byte[] bytes) : base(bytes)
{
WaveFormat = waveFormat;
}
public FastWaveBuffer(WaveFormat waveFormat, int size = 4096) : base()
{
WaveFormat = waveFormat;
Capacity = size;
}
public WaveFormat WaveFormat
{
get;
}
}
}