简体   繁体   中英

stopping sounds in c#

 private void guna2Button1_Click(object sender, EventArgs e)
    {
        if (guna2CheckBox2.Checked && guna2CheckBox1.Checked)
        {
            
            MessageBox.Show("Please Choose One Box only");

        }
        else
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = Environment.CurrentDirectory;
            ofd.ShowDialog();

            SoundPlayer player = new System.Media.SoundPlayer(ofd.FileName);
            player.Play();
        }
    }

    private void guna2Button2_Click(object sender, EventArgs e)
    {
        
    }
}

Hello am making something to let user enter his wav file to played, and another button to let him stop the sound, but can not use player enter `enter code here code here player Stop as it is out of context, any idea how to make the guna2Button stop the played sound in the else

You should make the SoundPlayer a field (define it at class-level). This makes it accessible to all methods in your class.

private SoundPlayer player;

private void guna2Button1_Click(object sender, EventArgs e)
{
    if (guna2CheckBox2.Checked && guna2CheckBox1.Checked)
    {
        MessageBox.Show("Please Choose One Box only");
    }
    else
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.InitialDirectory = Environment.CurrentDirectory;
        ofd.ShowDialog();

        player = new SoundPlayer(ofd.FileName);
        player.Play();
    }
}

private void guna2Button2_Click(object sender, EventArgs e)
{
    //Check if the player is null (not defined yet), otherwise this could cause a NullReferenceException
    if (player != null) {
        player.Stop();
    }
}

It's a good idea to learn about variable scope , as this is a very important aspect of C# (and pretty much every other programming language).

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