我想创建2个JMenuItem
,可以启动和停止背景音频。
这是我的代码:
public class MainClass extends JFrame
{
private AudioInputStream audioInputStream;
private Clip clip;
public MainClass(String title)
{
try
{
audioInputStream = AudioSystem.getAudioInputStream(new File("Background.wav"));
clip = AudioSystem.getClip();
clip.loop(Clip.LOOP_CONTINUOUSLY);
clip.open(audioInputStream);
}
catch(Exception e)
{
System.out.println("Error with playing sound.");
e.printStackTrace();
}
}
public void startSound()
{
clip3.start();
settingSubMenuItem1.setEnabled(false);
settingSubMenuItem2.setEnabled(true);
}
public void stopSound()
{
clip3.stop();
settingSubMenuItem1.setEnabled(true);
settingSubMenuItem2.setEnabled(false);
}
private class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == settingSubMenuItem1)
{
startSound();
}
if(e.getSource() == settingSubMenuItem2)
{
stopSound();
}
}
}
}
当我点击settingSubMenuItem1
时,它工作正常,播放音频。
但是,当我点击settingSubMenuItem2
时,会出现错误,如果再次点击settingSubMenuItem1
,则会发出更多声音。
以下是错误:
Error with playing sound.
java.lang.IllegalStateException: Clip is already open with format PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian and frame lengh of 7658
我的程序有什么错误?
答案 0 :(得分:2)
这里的SSCCE是一个'空结果',因为音频重启(尝试至少3次),没有例外。
import java.net.URL;
import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;
public class RestartableLoopSound {
public static void main(String[] args) throws Exception {
URL url = new URL(
"http://pscode.org/media/leftright.wav");
final Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JToggleButton b = new JToggleButton("Loop");
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (b.isSelected()) {
// loop continuously
clip.loop(Clip.LOOP_CONTINUOUSLY);
} else {
clip.stop();
}
}
};
b.addActionListener(listener);
JOptionPane.showMessageDialog(null, b);
}
});
}
}