Java 按钮无声音播放

3

我创建了一个class,以便在我点击按钮时播放声音。

以下是代码:

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下载的音频文件存在问题,因此无法播放。 @_@

3个回答

4

使用

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        playSound();
    }
});

3

这应该可以工作:

public class Test extends JFrame {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        JButton button = new JButton("play");
        button.addActionListener(new  ActionListener() {
        public void actionPerformed(ActionEvent e) {
                playSound();
        }});
        this.getContentPane().add(button);
        this.setVisible(true);
    }

    public void playSound() {
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("beep.wav"));
            Clip clip = AudioSystem.getClip( );
            clip.open(audioInputStream);
            clip.start( );
        }
        catch(Exception e)  {
            e.printStackTrace( );
        }
    }
}

请注意,在播放文件时,GUI 不会负责。使用 Joop Eggen 的方法在监听器中进行更正,这将以异步方式播放文件。
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        playSound();
    }
});

我什么也听不到... :( - T_01
你的扬声器开着吗? ;) - Thomas Uhrig
是的...我已经问过关于这个问题的问题,但是并没有得到任何答案 :/ - T_01

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接