2012-05-13 175 views
3

我創建了一個class來播放聲音,當我點擊按鈕。Java沒有聲音播放按鈕

下面是代碼:

public void playSound() 
    { 
     try 
     { 
      AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("beep-1.wav")); 
      Clip clip = AudioSystem.getClip(); 
      clip.open(audioInputStream); 
      clip.start(); 
     } 
     catch(Exception e) 
     { 
      System.out.println("Error with playing sound."); 
     } 
    } 

當我想實現它進入了ButtonListener方法,它看起來像沒有播放聲音。

這裏ButtonListener代碼:

private class ButtonListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      if (replayButton == e.getSource()) 
      { 
       playSound(); 
      } 
     } 
    } 

有什麼不好的代碼?

編輯:

基本上我試圖創建一個簡單的記憶遊戲,我想點擊時聲音添加到按鈕。

解決:

好像我從Soundjay下載有問題,因此,音頻文件不能播放的音頻文件。 @ _ @

回答

3

這應該工作:

public class Test extends JFrame { 

    public static void main(String[] args) { 
     new Test(); 
    } 

    public Test() { 
     JButton button = new JButton("play"); 
     button.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
       playSound(); 
     }}); 
     this.getContentPane().add(button); 
     this.setVisible(true); 
    } 

    public void playSound() { 
     try { 
      AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("beep.wav")); 
      Clip clip = AudioSystem.getClip(); 
      clip.open(audioInputStream); 
      clip.start(); 
     } 
     catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

請注意,文件的播放過程中,圖形用戶界面將不RESPONSABLE。在你的聽衆中使用Joop Eggen的方法來解決這個問題。它將播放異步文件。

SwingUtilities.invokeLater(new Runnable() { 
    public void run() { 
     playSound(); 
    } 
}); 
+0

我不這裏什麼... :( –

+0

是你的音箱上;) –

+0

是的......我已經問這個問題,但我的arent得到任何答案:/? –

4

使用

SwingUtilities.invokeLater(new Runnable() { 
    @Override 
    public void run() { 
     playSound(); 
    } 
});