Play Audio in Java Applet
Java has the feature of the playing the sound file. This program will show you how to play a audio clip in your java applet viewer or on the browser.
For this example we will be creating an applet called PlaySoundApplet.java to play sound. There are two buttons to play the sound in Loop and to Stop the sound.
The play() method of AudioClip object is used to play the sound while stop() method is used for stop the running audio clip suddenly.
Here is the code of the program :
In this example we have a class AudioClip, which is an abstract class. So, it can't be instantiated directly. But there a method called getAudioClip() of Applet class which can be used to create the object of AudioClip. There are two versions of getAudioClip() function:
- public AudioClip getAudioClip(URL url)
- public AudioClip getAudioClip(URL url, String name)
In this example we are using the second method:
audioClip = getAudioClip(getCodeBase(), "TestSnd.wav");
AudioClip class provides the following methods:
public abstract void play() - to play the sound only once
public abstract void loop() - to play the sound in loop
public abstract void stop() - to stop the playing sound
Here is the HTML code :
<APPLET CODE="PlaySoundApplet" WIDTH="200" HEIGHT="300"></APPLET>