tags:

views:

53

answers:

2

I'm working on setting up an alarm that pops up as a dialog with multiple sound file options the user can choose from. The problem I'm having is creating a sound player at the local level that I can close with a button. The problem I'm having is that the sound keeps looping when I close the form because the SoundPlayer doesn't exist within the button click event.

here's what I have:

 void callsound()
    {
        if (SoundToggle == 0) // if sound enabled
        {

            if ((SoundFile == 0) && (File.Exists(@"attention.wav")))
            {
                System.Media.SoundPlayer alarm = new System.Media.SoundPlayer(@"attention.wav");
                alarm.PlayLooping();
            }
       if ((SoundFile == 1) && (File.Exists(@"aahh.wav")))
            {
                System.Media.SoundPlayer alarm = new System.Media.SoundPlayer(@"aahh.wav");
                alarm.PlayLooping();
            }
     }

private void button1_Click(object sender, EventArgs e)
    {
        //alarm.Stop();  Only works if SoundPlayer declared at class level
        this.Close();
    }

Is there a way I can do what I want to do by declaring the SoundPlayer instances where I am? Or is there a way to declare it at the class level, and still be able to change the sound file based on user settings?

+1  A: 

Why is this a problem? SoundPlayer doesn't support playing more than one sound at the same time anyway. Move it to class scope, override OnFormClosing event, problem solved.

public partial class Form1 : Form {
  private System.Media.SoundPlayer alarm;

  protected override void OnFormClosing(CancelEventArgs e) {
    if (alarm != null) alarm.Stop();
  }
}
Hans Passant
It's a problem because this is my first time using SoundPlayer, and I"m still trying to figure it out.It's telling me "OnFormClosing" requires a return type. How can I go about getting that taken care of? I don't know what it wants.
EvanRyan
Ugh, make that a void. Post updated and verified this time.
Hans Passant
Thank you for the clarification. Now I'm going to see if I can figure out how to get it all pieced together. I'm still very new to C#, so this is all new to me right here.
EvanRyan
A: 

You can try:

SoundMixer.stopAll();

or

SoundMixer.soundTransform = new SoundTransform(0);

The SoundMixer class controls global sound, so it should stop everything in the same security sandbox.

redconservatory