Java no sound played for button

僤鯓⒐⒋嵵緔 提交于 2020-01-24 09:13:50

问题


I have created a class to play the sound when I click the buttons.

Here is the code :

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.");
        }
    }

When I want to implement it into the the ButtonListener method, it's seem like no sound is played.

Here the ButtonListener code :

private class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e) 
        {
            if (replayButton == e.getSource()) 
            {
                playSound();
            }
        }
    }

What's wrong with the code?

EDIT :

Basically I'm trying to create a simple memory game, and I want to add sound to the buttons when clicked.

SOLVED :

Seems like the audio file I downloaded from Soundjay got problem, and hence, the audio file can't be played. @_@


回答1:


This should work:

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( );
        }
    }
}

Note that during the play of your file, the GUI will be not responsable. Use the approach from Joop Eggen in your listener to correct this. It will play the file asynchronous.

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



回答2:


Use

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



回答3:


Any stacktrace, please??? did you add listener to the button???

Anyway the standart way have some bugs when targeting cross-platform. Use Java Media Framework at http://www.oracle.com/technetwork/java/javase/tech/index-jsp-140239.html.



来源:https://stackoverflow.com/questions/10570537/java-no-sound-played-for-button

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!