Jump to Real's How-to Main page

Play an audio file from an application

With Applet, the getAudioClip method() from the Applet package is used to play sound file. Starting with JDK1.2, getAudioClip() is now a static method. So it may be possible to use it without an Applet (i.e. in a regular Java application) with

java.applet.Applet.getAudioClip(URLofMySound);
Note: Since JDK1.2, Java can play WAV directly, see http://java.sun.com/docs/books/tutorial/sound/playing.html.

Another way is to use the undocumented sun.audio package.

import sun.audio.*;
...
...
 AudioPlayer p=AudioPlayer.player;
 try{
   AudioStream as =
      new AudioStream(new FileInputStream("aSound.au"));
   p.start(as);
   }
 catch(IOException err){
   err.printStackTrace();
   }

To play a sound from a JAR file (the .AU file in the JAR must be accessible via the CLASSPATH of course!) :

import java.io.*;
import java.net.*;

import sun.audio.*;

public class AppAudio {
  public static void main(String args[]) throws Throwable {
    InputStream in = AppAudio.class.getResourceAsStream(args[0]);
    AudioStream as = new AudioStream(in);
    AudioPlayer.player.start(as);
    Thread.sleep(5000);
  }
}

Since JDK1.3, you have also the javax.sound package, see this HowTo.


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]