我已经使用AudioInputStream在我的程序中插入了背景音频。
当我按下On时,背景音频将会播放,而Off将停止播放背景音频。
下面是我的音频播放部分的代码部分:
public void playSound(int i)
{
try
{
. //Others buttons sound
. //Others buttons sound
if(i == 3 || i == 4)
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("Background.wav"));
Clip clip3 = AudioSystem.getClip( );
clip3.open(audioInputStream);
if(i == 3)
{
clip3.loop(Clip.LOOP_CONTINUOUSLY);
clip3.start();
settingSubMenuItem3.setEnabled(false);
settingSubMenuItem4.setEnabled(true);
}
if(i == 4)
{
clip3.stop();
settingSubMenuItem3.setEnabled(true);
settingSubMenuItem4.setEnabled(false);
}
}
catch(Exception e)
{
System.out.println("Error with playing sound.");
e.printStackTrace();
}
}下面是ButtonListener部分:
private class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == settingSubMenuItem3)
{
playSound(3);
}
if(e.getSource() == settingSubMenuItem4)
{
playSound(4);
}
}
}当我按下On按钮时,我的代码可以播放音频,但是当我按下Off按钮时,它不工作。
编译和运行过程中没有错误。
我的代码有什么错误?
发布于 2012-05-20 00:10:48
audioInputStream变量AudioInputStream和Clip变量clip3是该方法的局部变量。您尝试停止的对象与当前正在播放的对象不同。
让它们成为类字段,在调用它们的方法之前检查它们是否为空,如果您试图停止当前正在播放的对象,请不要创建新对象,这样就可以了。
类似于:
public void playSound(int i) {
try {
// ...
if (i == 3 || i == 4) {
if (i == 3) {
audioInputStream = AudioSystem
.getAudioInputStream(new File("Background.wav"));
clip3 = AudioSystem.getClip();
clip3.open(audioInputStream);
clip3.loop(Clip.LOOP_CONTINUOUSLY);
clip3.start();
settingSubMenuItem3.setEnabled(false);
settingSubMenuItem4.setEnabled(true);
}
if (i == 4) {
if (clip3 != null && clip3.isActive()) {
clip3.stop();
settingSubMenuItem3.setEnabled(true);
settingSubMenuItem4.setEnabled(false);
}
}
}
} catch (Exception e) {
System.out.println("Error with playing sound.");
e.printStackTrace();
}
}同样,让audioInputStream和clip3成为非静态类字段。
顺便说一句,我会避免使用像3和4这样的“魔术”数字,因为这可能会在6个月后成为调试的魔鬼。取而代之的是为每个JButton提供自己的操作。它应该得到同样的回报。
https://stackoverflow.com/questions/10666827
复制相似问题