Reputation: 613
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. @_@
Upvotes: 3
Views: 2923
Reputation: 31605
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();
}
});
Upvotes: 3
Reputation: 109547
Use
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
playSound();
}
});
Upvotes: 4
Reputation: 175
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.
Upvotes: 2