简体   繁体   中英

C# Closing SoundPlayer on FormClosing

I've created a bool value named musiclose. I'm planning if this musiclose value is true, player will close, else it will continue playing.

public static bool musiclose;

Timer code is below:

timer1.Interval = 1000;
timer1.Start();

Here is the code:

public void timer3_Tick(object sender, EventArgs e)
{
    SoundPlayer player = new SoundPlayer(@"C:\Path\To\intro.wav");

    if (musiclose)
    {
        player.Stop();
        musiclose = false;
    }
}

How can I do that??

1) Do not recreate SoundPlayer instance everytime inside timer3_Tick() event. Create a global instance of SoundPlayer.

2) Implement form closing event, https://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing(v=vs.110).aspx

3) In the close event,

private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
    player.Stop();
    player.Dispose();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM