我创建了一个类
来在我点击按钮时播放声音。
代码如下:
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();
}
});
关于Java没有为按钮播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10570537/