Skip to content

Instantly share code, notes, and snippets.

@theArjun
Last active January 28, 2019 17:17
Show Gist options
  • Select an option

  • Save theArjun/c7b0c9816a4a4acfa250bad0a8b44730 to your computer and use it in GitHub Desktop.

Select an option

Save theArjun/c7b0c9816a4a4acfa250bad0a8b44730 to your computer and use it in GitHub Desktop.
Playing Audio in Applet

Playing Audio in Applet

28th January 2019 , πŸ–‹ Arjun Adhikari

An applet can play an audio file represented by the AudioClip interface in the java.applet package. The AudioClip interface has three methods, including :
public void play() βˆ’ Plays the audio clip one time, from the beginning.
public void loop() βˆ’ Causes the audio clip to replay continually.
public void stop() βˆ’ Stops playing the audio clip.
To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class. The getAudioClip() method returns immediately, whether or not the URL resolves to an actual audio file. The audio file is not downloaded until an attempt is made to play the audio clip.

Make sure you have file named sample.wav in the working directory :

AudioIsImportant

import java.awt.*;
import java.net.*; // For URL objects
import java.applet.*;
/*
<applet code = "PlayAudio" height = "400" width = "400">
<param name = "audioURL" value = "sample.wav">
</applet>
*/
// AppletContext is an environment (interface) which helps to communicate with outer-environment and deal with media files such as audio, image.
public class PlayAudio extends Applet {
public AudioClip myMusic; // Defining a variable of data type AudioClip.
public AppletContext context;
public void init() {
context = this.getAppletContext();
String audioURL = this.getParameter("audioURL"); // This gets the parameter passed from applet.
if (audioURL == null) {
audioURL = "sample.wav"; // If no parameter is passed.
}
try {
URL myURL = new URL(this.getDocumentBase(), audioURL); // New URL object storing audio URL passed by user.
myMusic = context.getAudioClip(myURL);
// myMusic = this.getAudioClip(myURL); // Also can be done like this.
} catch (MalformedURLException exc) {
exc.printStackTrace();
context.showStatus("Couldn't load audio file."); // Showing status to the Browser status bar.
}
}
public void start() { // When Applet starts
if (myMusic != null) {
myMusic.loop();
}
}
public void stop() { // When Applet stop
if (myMusic != null) {
myMusic.stop();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment