Java no sound for button

I created classto play 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 in a method ButtonListener, it seems that the sound is not playing.

Here is the code ButtonListener:

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

What is wrong with the code?

EDIT:

Basically, I am trying to create a simple memory game, and I want to add sound to the buttons when pressed.

SOLVED:

It appears that the audio file downloaded from Soundjay is having a problem, and therefore the audio file cannot be played. @_ @

+3
source share
3 answers

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

, . Joop Eggen , . .

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

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

Any stack please ??? did you add a listener to the button ???

In any case, the standard path has some errors when targeting the cross platform. Use the Java Media Framework at http://www.oracle.com/technetwork/java/javase/tech/index-jsp-140239.html .

+2
source

All Articles