(C#)按下按键时播放声音,再次按下按键时停止播放声音

时间:2020-04-14 19:03:39

标签: c# audio media

我正在尝试通过按键播放声音。到目前为止,我已经开始工作了。但是,当我再次按下该键时,声音会停止。我不想使用其他键停止播放声音。我想要一个。

    public class SCBA
    {
         static string GameDirectory;
         static string soundDirectory;
         static SoundPlayer player;


        public static void InitializeSound()
        {
            player = new SoundPlayer();
            GameDirectory = Directory.GetCurrentDirectory();
            soundDirectory = GameDirectory + "/test/test/test/Audio";
            Game.LogTrivial("Sound Directory located at" + soundDirectory);

            try
            {
                player.SoundLocation = soundDirectory + "/test.wav";
            }
            catch(Exception e)
            {
                string error = e.Message;
                Game.LogTrivial("Sound File located at" + player.SoundLocation);
                Game.LogTrivial(String.Format("Something happened" + error));


            }

        }

        public static void PlaySound()
        {
            try
            {
                player.Play();
            }
            catch (Exception e)
            {
                Game.LogTrivial(e.ToString());
                Game.LogTrivial(String.Format("Something happened", e.Message));

            }
        }
    }

这是我主类中的代码,记录是否按下了键

        if (Game.IsKeyDown(Settings.SCBA))
        {
            SCBA.PlaySound();
        }

2 个答案:

答案 0 :(得分:0)

在您的主类中定义一个布尔变量,然后向您的def start_requests(self): #print(self.website) url = 'https://www.amazon.com/s?k=water+balloons' yield scrapy.Request(url,callback=self.parse) 类中添加一个StopSound无效值。

SCBA

答案 1 :(得分:0)

这样,您无需更改主班

public class SCBA
{
     static string GameDirectory;
     static string soundDirectory;
     static SoundPlayer player;
     private static bool isPlaying;



    public static void InitializeSound()
    {
        player = new SoundPlayer();
        GameDirectory = Directory.GetCurrentDirectory();
        soundDirectory = GameDirectory + "/test/test/test/Audio";
        Game.LogTrivial("Sound Directory located at" + soundDirectory);
        isPlaying = false;

        try
        {
            player.SoundLocation = soundDirectory + "/test.wav";
        }
        catch(Exception e)
        {
            string error = e.Message;
            Game.LogTrivial("Sound File located at" + player.SoundLocation);
            Game.LogTrivial(String.Format("Something happened" + error));


        }

    }

    public static void PlaySound()
    {
        try
        {
            if(isPlaying)
            {
                player.Stop();
            }
            else
            {
                player.Play();
            }

            isPlaying = !isPlaying;
        }
        catch (Exception e)
        {
            Game.LogTrivial(e.ToString());
            Game.LogTrivial(String.Format("Something happened", e.Message));

        }
    }
}