2015-04-02 37 views
0

只要按下按鈕,我就想讓播放器播放聲音。按按鈕播放聲音

以下是我迄今所做的:

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

問題出在哪裏以及如何解決呢?

+0

您是否遇到錯誤或者什麼都沒有發生?你確定文件路徑是正確的嗎? 「dayz sounboard」缺少一個「d」,不知道這是否是故意的。 – 2015-04-02 20:07:36

+0

請將此事列出來:http://stackoverflow.com/questions/16702659/play-a-sound-while-key-is-down – 2015-04-02 20:08:31

+0

你確定wav文件的路徑,或者你有足夠的權限訪問那個目錄? – EZI 2015-04-02 20:09:34

回答

0

您可以嘗試在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事件。