'NAudio - Can not Replay the played sound

Here is my code:

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

It will play the audio once, If I Play it again, it will not play it. If I want to make a new Mp3FileReader every time to play the audio, the memory usage of my program will grow more and more.

I just need to use one WaveOut and play the sound in multiple threads as I can. possible?



Solution 1:[1]

Try wrapping the code in a using block:

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

This will make sure the the object is disposed properly

Edit:

new day new hope! as described here: 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();
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1