我希望声音播放器只要按一下按钮就可以播放。

到目前为止,这是我所做的:

public partial class Form1 : Form
{
    private SoundPlayer soundPlayer;

    private void FormMain_KeyPress(object sender, KeyPressEventArgs e)
    {
        if(e.KeyChar == 'n')
        {
            SoundPlayer s = new SoundPlayer(@"C:\Users\darude_rig\Desktop\dayz sounboard\media\sounds\AKM.wav");
            s.PlayLooping();
        }
    }
}

问题出在哪里,我该如何解决?

最佳答案

您可以尝试在KeyDown事件中初始化和/或循环SoundPlayer实例,然后在KeyUp事件中停止它。

public partial class Form1 : Form
{
    private SoundPlayer soundPlayer;

    private void FormMain_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.KeyCode == Keys.N)
        {
            if (soundPlayer == null)
                soundPlayer = new SoundPlayer(@"C:\Users\darude_rig\Desktop\dayz sounboard\media\sounds\AKM.wav");

            soundPlayer.PlayLooping();
        }
    }

    private void FormMain_KeyUp(object sender, KeyEventArgs e)
    {
        if(e.KeyCode == Keys.N)
        {
            if (soundPlayer != null)
                soundPlayer.Stop();
        }
    }
}

请记住在某处订阅表单KeyUp和KeyDown事件。

关于c# - 按下按钮即可播放声音,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29421502/

10-12 16:11