Search code examples
c#audioformclosing

C# Playing sound before closing form


I try to play a sound before closing my program. I set that sound for my Exit Button. Here is my code (I used the library WMPLib):

private void button1_Click(object sender, EventArgs e)
{
        WindowsMediaPlayer btnPlayer = new WindowsMediaPlayer();
        btnPlayer.URL = "Wrong.wav";
        btnPlayer.controls.play();
        //Thread.Sleep(2000); 
        this.Close();
}

My problem is: It exits immediately and doesn't play the sound. Please help! Thank you.


Solution

  • Your issue is that WindowsMediaPlayer.Play returns immediately.

    You should subscribe for the state change event like this:

    btnPlayer.PlayStateChange += this.PlayStateChange;
    

    And there:

    private void PlayStateChange(int NewState)
    {
        if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
        {
            this.Close();
        }
    }
    

    It's all here