Skip to content

Playing audio

Ralph Niemitz edited this page May 21, 2017 · 2 revisions

There are two classes important for playing audio. The first one is BufferedAudio and the second one is StreamedAudio. Before you start you should decide on which class to use. BufferedAudio is meant for small audio files(smaller than 2 seconds) which are played often while StreamedAudio is meant for large audio files like music.

Both classes behave mostly the same. However, there are some differences. BufferedAudio runs in a daemon thread while StreamedAudio does not. That means that you need one non-daemon thread in order to properly use BufferedAudio. And StreamedAudio calls its own close and open methods often. That is because not every AudioInputStream can be resetted. In order to reset, the stream has to be re-opened. This is no problem in BufferedAudio since all the audio data is in memory.

Once you decided which class to use, you initialize a new Audio object like so: Audio audio = new BufferedAudio("gunshot.wav") Before you can use the audio, you have to open it with open.

Now you can access methods like play, loop, pause, resume or stop.

IMPORTANT!
If you are done using the Audio instance you have to close it with close in order to free the used resources and prevent memory leaks.

Example:

try {
	
	Audio audio = new StreamedAudio("music.mp3");
	audio.addAudioListener(event -> {
	
		if(event.getType() == AudioEvent.Type.REACHED_END) {
		
			event.getAudio().close();
		}
	});
	audio.open();
	audio.play();

} catch(AudioException exception) {

	exception.printStackTrace();
}
Clone this wiki locally