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 the getAudioClip(URL url) API method to get the AudioClip object specified by URL and name arguments.
  • In paint(Graphics g) method call play() API method of AudioClip to start playing this audio clip. Call stop() API method of AudioClip to stop playing this audio clip. Call loop() 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button