APPLETS AND SOUND

CONTENTS

1. Introduction
2. Example Applet



1. INTRODUCTION

The Applet package contains a interface AudioClip. Java compatible sounds are currently limitted to .au files (an audio format). If you go to the Oxford University Computing Laboratory Sound Archive you will find a number of example sounds. If you click on "Sun demonsration sounds" you will find a number of sample .au files which you can down load.

To play a sound you must first create an instance of the class AudioClip, get the sound using the method getAudioClip from the Applet class and then play it using the method play from the AudioClip class.




2. SIMPLE EXAMPLE

Some example code is given in Table 1 that plays some of the "Sun demonsration sounds". The example is based on that given in Holmes (1998).

// Applet Example (Sound)
// Frans Coenen
// Dept. Comp. Sci., University of Liverpool
// Friday 19 January 20001

import java.awt.event.*;
import java.awt.*;
import java.applet.*;

public class SoundEx extends Applet implements ActionListener {

    /* ------ FIELDS ------ */
    
    AudioClip sound;
    // Array of sound names 
    String[] soundNames = {"bark","bong","bubbles","busy","chirp","clink",
    		"cowbell","crash","cuckoo","drip","gong","splat"};
    // Array of buttons
    Button[] button = new Button[soundNames.length];
    		
    /* ------ METHODS ------ */
    
    /* Override init() */
    
    public void init() {
        setLayout(null);
        
        // Add buttons
        
	for (int index=0;index < soundNames.length;index++) {
            button[index] = new Button(soundNames[index]);
	    button[index].setLocation(10,10+(45*index));
	    button[index].setSize(120,40);
	    button[index].setBackground(Color.cyan);
	    button[index].addActionListener(this);
	    add(button[index]);
	    }
        }

    /* Action Listener */
    
    public void actionPerformed(ActionEvent event) {
        String source = event.getActionCommand();
	
	for (int index=0;index < soundNames.length;index++) {
	    if (source.equals(soundNames[index])) {
	        // Play the audio clip
		sound = getAudioClip(getCodeBase(),source.toString()+".au");
		sound.play();
		return;
		}
	    }
        }
    }

Table 1: Sound applet

The associated .html file is given in Table 2 below; click here to view the effect.

.

< HTML >
< HEAD >
< TITLE >APPLET EXAMPLE (SOUND)< /TITLE >
< /HEAD >
< BODY >
< H1 >APPLET EXAMPLE (SOUND)< /H1 >
< CENTER >
< APPLET code=SoundEx.class width=140 height=550 >
< /APPLET >
< /CENTER >
< /BODY >
< /HTML >   

Table 2: "sound" HTML file

REFERENCES

Holmes, B. (1998).
Programming with Java. Jones and Bartlett, Boston MA



Created and maintained by Frans Coenen. Last updated 31 January 2001