NAudio - 无法重播播放的声音

NAudio - Can not Replay the played sound

这是我的代码:

var w = new WaveOut();
var wf = new Mp3FileReader(new MemoryStream(Resources.click));
w.Init(wf);
w.Play();

它会播放一次音频,如果我再Play它就不会播放了。如果我每次都想新建一个Mp3FileReader来播放音频,我的程序内存占用会越来越大。

我只需要使用一个 WaveOut 并尽可能在多个线程中播放声音。可能吗?

尝试将代码包装在 using 块中:

using (var stream = new MemoryStream(Resources.click))
{
   var wf = new Mp3FileReader(stream);
   var w = new WaveOut();
   w.Init(wf);
   w.Play();
   //w.Dispose(); //maybe? maybe not?
}

这将确保正确处理对象

编辑:

新的一天新的希望! 如此处所述: https://csharp.hotexamples.com/de/examples/NAudio.Wave/WaveOut/Play/php-waveout-play-method-examples.html

 public void PlaySound(string name, Action done = null)
 {
     FileStream ms = File.OpenRead(_soundLibrary[name]);
     var rdr = new Mp3FileReader(ms);
     WaveStream wavStream = WaveFormatConversionStream.CreatePcmStream(rdr);
     var baStream = new BlockAlignReductionStream(wavStream);
     var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback());
     waveOut.Init(baStream);
     waveOut.Play();
     var bw = new BackgroundWorker();
     bw.DoWork += (s, o) =>
                      {
                          while (waveOut.PlaybackState == PlaybackState.Playing)
                          {
                              Thread.Sleep(100);
                          }
                          waveOut.Dispose();
                          baStream.Dispose();
                          wavStream.Dispose();
                          rdr.Dispose();
                          ms.Dispose();
                          if (done != null) done();
                      };
     bw.RunWorkerAsync();
 }

我已经找到解决办法,我们可以重置内存流位置,在不占用内存的情况下再次播放音频:

audio = new Mp3FileReader(new MemoryStream(Resources.click)); // audio is global
player = new WaveOut(); // player is also global
player.Init(audio);

然后每当我们需要播放声音时,我们将这样做:

audio.Seek(0, SeekOrigin.Begin);
player.Play();