applet
Play audio in Applet
In this example we shall show you how to play audio in an Applet. A Java applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass of the java.applet.Applet class. The Applet class provides the standard interface between the applet and the browser environment. To play audio in an Applet one should perform the following steps:
- Create a class that extends the Applet, such as
PlayAudioInApplet
class in the example. - Use
init()
API method of Applet. This method is called by the browser or applet viewer to inform this applet that it has been loaded into the system. In this method call thegetAudioClip(URL url)
API method to get the AudioClip object specified by URL and name arguments. - In
paint(Graphics g)
method callplay()
API method of AudioClip to start playing this audio clip. Callstop()
API method of AudioClip to stop playing this audio clip. Callloop()
API method of AudioClip to start playing this audio clip in a loop,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.applet.Applet; import java.applet.AudioClip; import java.awt.Graphics; public class PlayAudioInApplet extends Applet { private static final long serialVersionUID = 2530894095587089544L; private AudioClip clip; // Called by the browser or applet viewer to inform // this applet that it has been loaded into the system. public void init() { clip = getAudioClip(getDocumentBase(), "http://www.myserver.com/clip.au"); } // Paints the container. This forwards the paint to any // lightweight components that are children of this container. public void paint(Graphics g) { // Start playing this audio clip. Each time this method is called, // the clip is restarted from the beginning. clip.play(); // Stops playing this audio clip. clip.stop(); // Starts playing this audio clip in a loop. clip.loop(); } }
This was an example of how to play audio in Applet in Java.