There are two ways you can play a sound file:
The simple way is to use a static method newAudioClip() of an Applet class to get an instance of AudioClip, then invoke the play method.
For example:
JButton logout = new JButton( "Logout" );
logout.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent evt )
{
// play a sound before loging out
try
{
java.applet.AudioClip clip =
java.applet.Applet.newAudioClip(new java.net.URL( "file:/logout.wav"));
clip.play();
// loging out.....
}
catch( Exception e ) {}
}
});
The alternative way, which is a right way to do, is using the Java Sound API. You need to learn the following classes of Java Sound API in order to play a sound file successfully:
- AudioInputStream
- AudioFormat
- DataLine
- SourceDataLine
Hope this help.
|