[英]Java no sound played for button
当我点击按钮时,我创建了一个播放声音的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下载的音频文件有问题,因此无法播放音频文件。 @ _ @
采用
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
playSound();
}
});
这应该工作:
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( );
}
}
}
请注意,在播放文件期间,GUI将不负责任。 在你的监听器中使用Joop Eggen的方法来纠正这个问题。 它会异步播放文件。
SwingUtilities.invokeLater(new Runnable() {
public void run() {
playSound();
}
});
任何堆栈跟踪,请??? 你有没有添加监听器按钮???
无论如何,当针对跨平台时,标准方式会有一些错误。 请访问http://www.oracle.com/technetwork/java/javase/tech/index-jsp-140239.html使用Java Media Framework。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.