小编典典

播放AudioInputStream时出错

java

我想创建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

我的程序有什么错误?


阅读 380

收藏
2020-11-26

共1个答案

小编典典

此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);
            }
        });
    }
}
2020-11-26