Pages

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




7 comments:

  1. THANK YOUUUUU THIS WORKS PERFECT YOU'RE DA BESTTT!

    ReplyDelete
  2. SIMPLY PERFECT. THANK YOU!

    ReplyDelete
  3. what if it is joptionpane not jbutton can it work in joptionpane??

    ReplyDelete
  4. Thank You so much.It works completely.Thank u...

    ReplyDelete
  5. Dont seem to get it to work. Please help

    ReplyDelete