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




9 comments:

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

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

    ReplyDelete
  3. That was really impressive

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

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

    ReplyDelete
  6. How can i remove/ stop playing this audio while another button action is performed, can u please help me

    ReplyDelete
  7. how to call the function with the filename as string:

    ReplyDelete
  8. THANK YOU OH MY GOD!!!!!!!!

    ReplyDelete