Play MP3 using SoundPlayer after conversion to WAV using NAudio

后端 未结 2 597
Happy的楠姐
Happy的楠姐 2021-01-19 15:47

I want to play MP3 file downloaded from the web using NET provided System.Media.SoundPlayer mechanism. As it works with WAV formats, it requires the support of e.g. NAudio l

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-19 16:21

    Based on Lee Harrison answer, I've created alternative code which is better.

    (3) plays directly MP3 file from WEB without conversion to WAV and without usage of disk operations:

    public void Speak(Uri mp3FileUri)
    {
        using (var client = new WebClient())
        {
            using (var networkStream = client.OpenRead(mp3FileUri))
            {
                if (networkStream != null)
                {
                    using (var memStream = new MemoryStream())
                    {
                        networkStream.CopyTo(memStream);
                        memStream.Position = 0;                            
                        using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                        {
                            var waveEvent = new ManualResetEvent(false);
                            waveOut.PlaybackStopped += (sender, e) => waveEvent.Set();
                            waveEvent.Reset();
                            using (var rdr = new Mp3FileReader(memStream))
                            using (var waveStream = WaveFormatConversionStream.CreatePcmStream(rdr))
                            using (var baStream = new BlockAlignReductionStream(waveStream))
                            {
                                waveOut.Init(baStream);
                                waveOut.Play();
                                if (waveOut.PlaybackState != PlaybackState.Stopped)
                                { 
                                    waveEvent.WaitOne(); /* block thread for a while because I don't want async play back                                
                                                            (to be analogical as usage of SoundPlayer Play method) */
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    

    Nevertheless (despite this is quite good for me), I still don't know what's the problem with sample (2).

提交回复
热议问题