Java Java intro
  1. Java intro
  2. Java basics
Java core
  1. Java variables
  2. Java conditionals
  3. Java loops
  4. Java arrays
  5. Java strings
Object-oriented Java
  1. Java OOP 1
  2. Java OOP 2
  3. Java packages
  4. Java interfaces
Java interactive
  1. Java user input
  2. Java exceptions
  3. Java events
Graphical Java
  1. Java GUI
  2. Java GUI layout
  3. Java graphics
Java extras
  1. Java applets
  2. Java sounds
  3. Java random numbers
Java wrap-up
  1. Java summary

Java audio

Java provides the ability to play audio in applications and applets.

This tutorial focuses on:

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.

AudioClip aClip;

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.

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:

Complete audio file playing program:
import java.awt.*; import java.awt.event.*; import java.applet.*; import*; 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){; } if (e.getSource() == loop){ bach.loop(); } if (e.getSource() == stop){ bach.stop(); } } }

What it will look like:

Sound frame
© Copyright 2013-2014
Terms of use | Privacy policy | Copyright information