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");}
THANK YOUUUUU THIS WORKS PERFECT YOU'RE DA BESTTT!
ReplyDeletewhat if it is joptionpane not jbutton can it work in joptionpane??
ReplyDeleteThat was really impressive
ReplyDeleteThank You so much.It works completely.Thank u...
ReplyDeleteDont seem to get it to work. Please help
ReplyDeleteDoesnt work
ReplyDeleteHow can i remove/ stop playing this audio while another button action is performed, can u please help me
ReplyDeletehow to call the function with the filename as string:
ReplyDeleteTHANK YOU OH MY GOD!!!!!!!!
ReplyDelete