开发者

Stopping a SoundPlayer loop at the local level

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 does开发者_开发技巧n'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?


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();
  }
}


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.


Using Powershell, I was playing with playing .wav files and started a repeating loop using the following:

$Playwav = new-object ('Media.SoundPlayer') $playpath1 
$Playwav.PlayLooping()

I stopped the loop inside Powershell IDE by Run Section (F8):

$Playwav = new-object ('Media.SoundPlayer') $playpath1 
$Playwav.PlayLooping()
$Playwav.stop()

FWIW, the .wav in my example was FPS Doug takethatbitch.wav. So the runaway loop made me laugh.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜