JaVa
   

app 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 app 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 app
import java.applet.*;
import java.io.*;
import java.net.*;
public class SimpleSoundapp
{
 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();
 }
}


Java End example

When we execute the app, 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
   
Comments