Playing Sound in Java

By | April 18, 2014

This isn’t much of a post, but I’ll put it here for anyone (especially a current tutoring student) who needs it. The SoundClip class I’ve provided can be used to load and play an audio file from within the current JAR’s res folder.

Usage

In this example, the code will load the file “res/sounds/brick-hit.wav” and play it.

Screen Shot 2014-04-18 at 3.57.36 PM


public class SoundTest {

	public static void main(String args[]) {
		SoundClip brickHit = new SoundClip("sounds/brick-hit.wav");
		brickHit.play();
	}

}

SoundClip Code


import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class SoundClip {

	Clip clip;

	/**
	 * Loads a sound file from the resource folder
	 */
	public SoundClip(String fileName) {

		try {
			clip = AudioSystem.getClip();
			clip.open(AudioSystem.getAudioInputStream(getClass().getResourceAsStream(fileName)));
		} catch (Exception e) {
			e.printStackTrace();
			clip = null;
		}

	}

	/**
	 * Play the sound clip
	 */
	public void play() {
		if( clip != null ) {
			clip.stop();
			clip.setFramePosition(0);
			clip.start();
		}
	}

	/**
	 * Stop the sound clip
	 */
	public void stop() {
		if( clip != null )
			clip.stop();
	}

	/**
	 * Play the audio clip in a loop
	 */
	public void loop() {
		if( clip != null )
			clip.loop(Clip.LOOP_CONTINUOUSLY);
	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *