Images & Audio Clips

Developing Animation

For developing animation programs, refer Image and Animation topic.

Playing Audio-clips

Playing music in an applet is very trivial. The audio files can be of any type – like .au, .wav or .mp3 etc. To support audio, the java.applet package comes with an interface AudioClip. An object of AudioClip interface can be obtained using the Applet method getAudioClip(). The AudioClip interface contains three methods to play the music – play() which plays only once the music, loop() which plays continuously and stop() method to stop the music.

Using AudioClip Methods

In the following program, all the three methods play(), loop() and stop() of AudioClip are used. To call these methods, three buttons are created and when a button clicked, the appropriate method is called.

File Name:

import java.applet.*; 
import java.awt.*; 
import java.awt.event.*; 

public class PlayLoopStop extends Applet implements ActionListener
  AudioClip clip;
  public void init()
    clip = getAudioClip(getDocumentBase(),"");
    Button pb = new Button("PLAY");
    Button cb = new Button("CONTINUOUS");
    Button sb = new Button("STOP");

    add(pb);  add(cb);  add(sb);
  public void actionPerformed(ActionEvent e)
    String str = e.getActionCommand();
    else if(str.equals("CONTINUOUS"))
    else if(str.equals("STOP"))

File Name: Music.html

clip = getAudioClip(getDocumentBase(),"");

The getAudioClip() method of Applet returns an object of AudioClip, clip. The method requires two parameters, the first one is the address of the "" file as a URL object and the second is the name of the audio file. Place "" file in the current directory (where your applet exists). getDocumentBase() method of Applet returns an object of URL. The URL gives the address of the audio file.

play() method plays the music only once and then stops automatically. loop() method plays the music continuously. stop() method stops the music played with loop() method.

Note: Place some audio player software like Media Player or VLC Player are loaded. Keep the speakers on.

Leave a Comment

Your email address will not be published.