How do you expect to end the sound in Naudio?



  • My program needs to reproduce a few times a sound. How to do this one time, and now that I reproduce two times the biper starts drinking right after the music starts to reproduce, interrupting it. Say what's wrong?

        public void playmusic(int ce)
        {
            int i=0;            
            if (ce > 1)
            {
                while (i < 3 && i<ce)
                {
                    if (i == 0 && ce==1)
                    {
                        Console.Beep(500, 1000);
                        Thread.Sleep(500);
                        PlayMp3();
                        Thread.Sleep(1000);
                    }
                    else{
                    Console.Beep(500, 500);
                    Thread.Sleep(500);
                    PlayMp3();
                    Thread.Sleep(1000);}           
                    i++;
                }
            }
        }
    
    private void PlayMp3()
    {
        this.waveOut = new WaveOut(); 
        this.mp3FileReader = new Mp3FileReader("peep.mp3");
        this.waveOut.Init(mp3FileReader);
        this.waveOut.Play();
        this.waveOut.PlaybackStopped += OnPlaybackStopped;
    }
    
    private void OnPlaybackStopped(object sender, EventArgs e)
    {
        CloseWaveOut();
    }
    
    void CloseWaveOut()
    {
        if (waveOut != null)
        {
            waveOut.Stop();
        }
        if (mp3FileReader != null)
        {
            mp3FileReader.Dispose();
            mp3FileReader = null;
        }
        if (waveOut != null)
        {
            waveOut.Dispose();
            waveOut = null;
        }
    }
    



  • Play is performed in a separate flow. ManualResetEvent:

    using NAudio.Wave;
    using System.Threading;
    

    static void Main(string[] args) {
    var w = new WaveOut();
    var r = new Mp3FileReader(@"c:\temp\test.mp3");
    w.Init(r);
    w.Play();
    var re = new ManualResetEvent(false);
    w.PlaybackStopped += (s, e) => re.Set();
    mre.WaitOne(); // ждем вызов re.Set()
    Console.WriteLine("done");
    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2