Pages

Showing posts with label Button click. Show all posts
Showing posts with label Button click. Show all posts

Saturday, 4 June 2011

Add sound on Jbutton click in Java

To add a sound on JButton click event, follow three simple steps:
1. Import the following:

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.Clip;
import javax.sound.sampled.AudioSystem;

2. Add the following function to your class:

public void playSound(String soundName)
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile( ));
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
clip.start( );
}
catch(Exception ex)
{
System.out.println("Error with playing sound.");
ex.printStackTrace( );
}
}

3. In your actionPerformed function for the JButton, just call the function with the filename as string:

public void actionPerformed(ActionEvent ae)
{

//do something
playSound("buzzer.wav");
}