Java audio
Java provides the ability to play audio in applications and applets.
This tutorial focuses on:
- The AudioClip interface
- The newAudioClip method
- Methods of the AudioClip interface
The AudioClip interface
To be able to play audio in a program or applet, you first have to use the AudioClip interface and instantiate an AudioClip object with it. The AudioClip interface is located in the java.applet package.
The newAudioClip method
After instantiating an AudioClip object, you have to load the actual audio file to be played. This is achieved with the newAudioClip method - a static method of the Applet class which takes an instance of the URL class that loads the file.
Example:aClip = Applet.newAudioClip(new URL("file:sound.wav"));
In the above example, an audio file named sound.wav is loaded as the audio file to be played.
Methods of the AudioClip interface
Once the audio file is uploaded, you can use the methods of the AudioClip interface to work with it.
Methods of the AudioClip interface:
-
loop() - will play an audio file continuously
-
play() - will play an audio file once
-
stop() - will stop an audio file while it is playing
Complete audio file playing program:import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
class AudioFrame extends Frame implements ActionListener{
AudioClip bach;
Button play, loop, stop;
public AudioFrame(){
play = new Button("Play");
play.addActionListener(this);
add(play);
loop = new Button("Loop");
loop.addActionListener(this);
add(loop);
stop = new Button("Stop");
stop.addActionListener(this);
add(stop);
try{
bach = Applet.newAudioClip(new URL("file:bach.mid"));
}
//if there is a problem with the URL
//then this is the exception to be used
catch (MalformedURLException mfe){
System.out.println("An error occured, please try again...");
}
setLayout(new FlowLayout());
setSize(220, 150);
setVisible(true);
}
public static void main(String[] args){
AudioFrame AF = new AudioFrame();
}
public void actionPerformed(ActionEvent e){
//the action event handler tracks which button
//is pressed and performs an action accordingly
if (e.getSource() == play){
bach.play();
}
if (e.getSource() == loop){
bach.loop();
}
if (e.getSource() == stop){
bach.stop();
}
}
}
What it will look like: