How to play a MP3 file using NAudio

為{幸葍}努か 提交于 2019-11-27 02:49:06

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/2488426/how-to-play-a-mp3-file-using-naudio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!