简体   繁体   中英

Java no sound played for button

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. @_@

Use

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM