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