2

我想创建 2JMenuItem可以启动和停止背景音频。

这是我的代码:

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

我的程序有什么错误?

4

1 回答 1

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);
            }
        });
    }
}
于 2012-05-20T03:10:18.777 回答