Stopping a SoundPlayer loop at the local level

拜拜、爱过 提交于 2019-12-25 01:26:09

问题


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:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2916505/stopping-a-soundplayer-loop-at-the-local-level

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!