Return to article

Adding Sound: Example10Applet


Here are the important methods for loading, starting, and stopping music in an animation. The animation will have a continuous background soundtrack, as well as a bloop sound that is repeated each time Duke waves. The code for the entire applet can be found in Example10Applet.java.

    AudioClip background;
    AudioClip bubble;

    /**
     * Initialize the applet and compute the delay between frames.
     */
    public void init() {
	String str = getParameter("fps");
	int fps = (str != null) ? Integer.parseInt(str) : 10;
	delay = (fps > 0) ? (1000 / fps) : 100;

	tracker = new MediaTracker(this);
	frames = new Image[10];
	for (int i = 1 ; i <= 10 ; i++) {
	    frames[i-1] = getImage(getCodeBase(), "duke/T" + i + ".gif");
	    tracker.addImage(frames[i-1], 0);
	}

	background = getAudioClip(getCodeBase(), "audio/spacemusic.au");
	bubble = getAudioClip(getCodeBase(), "audio/bubble1.au");
    }

    /**
     * This method is called when the applet becomes visible on
     * the screen. Create a thread and start it.
     */
    public void start() {
	animator = new Thread(this);
	animator.start();
	// Start the background music
	background.loop();
    }

    /**
     * This method is called when the applet is no longer
     * visible. Set the animator variable to null so that the
     * thread will exit before displaying the next frame.
     */
    public void stop() {
	animator = null;
	offImage = null;
	offGraphics = null;
	// Stop the background music
	background.stop();
    }

    /**
     * Paint a frame of animation.
     */
    public void paintFrame(Graphics g) {
	// Only paint when all images have arrived
	if (tracker.statusID(0, true) == MediaTracker.COMPLETE) {
	    g.drawImage(frames[frame % 10], 0, 0, null);
	}
	// Play the bubble audio when Duke waves
	if ((frame % 10) == 3) {
	    bubble.play();
	}
    }