English 中文(简体)
How to play a MP3 file using NAudio
原标题:
  • 时间:2010-03-21 19:35:21
  •  标签:
  • c#
  • mp3
  • naudio
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?

最佳回答

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();

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;
        }
    }
}





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签