2012-05-13 7 views
3

버튼을 클릭 할 때 소리를 재생하기 위해 class을 만들었습니다.자바 버튼이 재생되지 않음

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

이 작동합니다 : 파일의 재생 중에, GUI를하지 responsable 될 것

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

참고. 리스너에서 Joop Eggen의 접근 방식을 사용하여이 문제를 해결하십시오. 비동기 파일을 재생합니다.

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

내가 아무것도 여기 해달라고 ... :( –

+0

은 스피커에있는) –

+0

예 ... 난 이미이에 대한 질문과 대답하지만 난 어떤 대답을 받고이 arent : / –

4

사용

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