Sound Stuff

<< CanyonAnimation | FinalProjectsTrailIndex | Bounce >>

The AudioClip method of the Applet class works well as a sound effect. In an application, this dont work as well. There are "work-arounds as described here, and even aYouTube tutorial, but they only work well as a background sound loop. As a sound effect, the sound is slow to load and clips a bit.

to play it once, use the play() method, to play it over and over again use the loop() method.

In Applications

Another approach to use a sound in an application is to make use of the Applet class within a Sound class.

JavaSound.java

import java.net.URL;
import java.applet.*;
public class JavaSound {
	private String fileName;
	private AudioClip player;
	public JavaSound(String file){
		fileName=file;
		player=null;
	}
	public void play() {
		try {
			URL soundToPlay = getClass().getResource(fileName);
			player = Applet.newAudioClip(soundToPlay);
			player.play();
		} catch (Exception e) {}
	}	
}

JavaSoundTester.java

public class JavaSoundTesterApp {
	public static void main(String[] args) {
		System.out.println("Initializing Sound effect");
		JavaSound boing=new JavaSound("boing.wav");
		System.out.println("Now playing it ");		
		boing.play();
	}	
}