libgdx part 7 – audio

Audio with libgdx is really really simple. You have three ways to output sound: either you output sound effects fully loaded into RAM for things like gun shots or you stream music in the background from a file (which wouldn’t fit into RAM) or you write PCM data directly to the audio device. The interfaces that encapsulate these 3 types of sound output are called Sound, Music and AudioDevice. The interface you can create new instances of these interfaces is called Audio which can be retrieved from an Application via the Application.getAudio() method. The Audio interface looks like this:

Easy. You pass a FileHandle to the first two methods which you retrieve via the Files instance we discussed in the last article. When you create a new AudioDevice you specify whether it should be mono or stereo. It will have it’s sample rate set to 44100Hz automatically. Let’s have a look at what we can do once we obtained an instance of Sound, Music and AudioDevice.

The Sound interface is pretty simple:

The first two methods make the Sound effect play, the second one takes a volume argument which should be in the range [0,1]. As with all resources created via libgdx you have to release the Sound instance via a call to Sound.dispose once it’s no longer used. Note that you can invoke the play methods multiple times and it will play the sound effect overlapped with any other audio that was previously played.

The Music interface looks like this:

I think i don’t have to explain a lot here, the interface is pretty similar to the MediaPlayer class on Android. Play, pause, stop, set looping, set volume are all straight forward. Again, after the Music instance is no longer used you have to dispose it via a call to Music.dispose(). Once interesting fact about the Music implementation for Android is that it will automatically pause and resume any Music instance that’s currently playing when the Activity gets paused and resumed. No need for you to handle that!

Finally there’s the AudioDevice interface for the die hard audio geeks:

We have a getter that tells you whether the device is mono or stereo. We also have two methods for writting samples to the audio device. You just pass in either short or float PCM data, interleaving the samples in the order left/right if the device is stereo. You have to dispose the AudioDevice once it is no longer used (make that our mantra of the day: dispose, dispose, dispose).

And that’s all their is to audio with libgdx. One word on supported formats: libgdx can playback WAV, OGG and MP3 on the desktop and Android. That should suffice for almost all of your needs.

Leave a Reply

Your email address will not be published.