有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

音频Java按钮无声音播放

我已经创建了一个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) 个答案

  1. # 1 楼答案

    这应该是有效的:

    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();
        }
    });
    
  2. # 2 楼答案

    使用

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