Application Simple Sound Example

In this example, we will load and play the same sound, as we did in the previous example, but this time we are going to create an application instead of an applet. Let's look at the entire example source code now.

Code Listing 11-3: Loading and playing a sound in an application

start example
import java.applet.*; import java.io.*; import java.net.*;     public class SimpleSoundApplication {     public static void main(String args[])     {         File soundFile = new File("siren.wav");                  AudioClip theSound = null;         try         {             theSound = Applet.newAudioClip(soundFile.toURL());         }         catch(MalformedURLException e)         {             System.out.println(e);             }                  // Play the audio clip...         theSound.play();     } }
end example

When we execute the application, a console window will appear and the siren.wav sound sample will be played. Let's now look at how the code works.

First we load in the file by creating a new File object, passing the name of our wav file (siren.wav) into the constructor. This can be seen here:

File soundFile = new File("siren.wav");

Next, we need to create an AudioClip object by passing a URL object into the constructor. As you know, we currently have a File object representing our sound, so we need to first convert this into a URL by calling the conveniently named toURL method of the File object. This can be seen here:

AudioClip theSound = null; try {     theSound = Applet.newAudioClip(soundFile.toURL()); } catch(MalformedURLException e) {     System.out.println(e);     } 

As you can see, we use the newAudioClip static method of the Applet class, which allows us to pass in a URL for the location of the sound. Using our file object, calling its toURL method, we create a new AudioClip object called theSound.

Once it is loaded, we then simply call the play method, as we did in the applet example. Note that we are still using the AudioClip class to store our sound, so the loop and stop methods are also available to us.



Java 1.4 Game Programming
Java 1.4 Game Programming (Wordware Game and Graphics Library)
ISBN: 1556229631
EAN: 2147483647
Year: 2003
Pages: 237

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net