Incorporating Sound in an Applet
Section 2 -Stopping the Sound.

 

In this example, the quote is the same as the last example. Browsing to another page will still allow the quote to finish uninterrupted. In contrast, the clip of the bluejay that is in the continuous loop, is stopped when the page is exited. In order to stop the sound of the bluejay, the clip.stop command must be used. When an applet is running in an HTML page, the stop method is called when you exit that page. By including a conditional statement ( if the clip is not equal to null, then stop it) in the stop method, the bluejay sound clip will end when you exit the page.

The code for this Java sound applet is listed below.

 

import java.applet.AudioClip;

public class sound2 extends java.applet.Applet
{



This allows us to use the Audioclip and
play methods in the Applet class of the
Java Abstract Windowing toolkit.


We want to generate an applet .
AudioClip clip;

public void stop() {
if (clip!=null) clip.stop();
}


Create an instance, clip, of the class AudioClip

Create a stop method &
Place the conditional: if the clip is running, stop it,
within the method.

The quote is NOT included here so it will
continue to play, as it did before, until it is done.
public void init()
{
play(getCodeBase(),"quote.au");
clip = getAudioClip(getCodeBase(),"jay.au");
clip.loop();
}

}
Start playing the clips in the init method.

Play the quote directly once.
Declare clip as an instance of the class AudioClip
and loop to repeat the call of the bluejay.

Both files are in the same directory as the applet.

The easiest way to copy the code for this example is to click here, copy the contents of the screen that loads in your browser , paste it in a text editor and save it in a file called "marque2.java".

After compiling this program we need to create an HTML page with a reference to the class file. It does not need a graphic window unless you are running it with an image or animation.

Save the HTML code in the same directory as the class file.

When you load the HTML file in your browser the applet will execute within the window.

You may have noticed by now that once you leave the HTML page containing the Applet, the bluejay sound stops and does not restart when you return to the page. It will start again only when you reload the page. The next section will cover the start method that will enable us to restart the sound when we simply hit the 'back' button on the browser and return to the page.

Starting, stopping, and starting sound again

Go to the next topic: Simple Animation

Back to the Table of Contents