Game Development Reference
In-Depth Information
However, Ogg support is not available for the robovm version
because iOS doesn't support it.
There are two interfaces, namely
Music
and
Sound
. They serve two different use
cases of playing back audio files. In terms of LibGDX, sounds are audio files that
usually play no longer than one second; think of laser or machine gun sounds. Audio
files used as
Sound
objects are loaded and decoded so that they can be directly sent
to the audio device. Obviously, the decoded audio data kept in memory can heavily
increase the overall memory usage. On the contrary, audio files are used as the
Music
objects are streamed, which means that only the necessary portion of it is decoded
and held in memory. Therefore, the
Music
objects should be used for playing long
audio files, such as background music.
The
Music
objects may require more CPU cycles because the
streamed audio data needs to be decoded before it can be sent to the
audio device. This is not the case with the
Sound
objects because
they are already decoded upon loading. So, it is simply a trade-off
between performance and memory usage.
The next sections will give you an overview of LibGDX's
Sound
and
Music
interfaces.
Exploring the Sound interface
The
Sound
interface is suitable for playing back short audio files. New sound
instances can be requested from LibGDX's
Gdx.audio
module using the
newSound()
method as follows:
Sound sound = Gdx.audio.newSound(
Gdx.files.internal("sound.wav"));
This line of code will allocate new memory for the decoded audio data of the
sound.
wav
file. The
Sound
interface also makes use of the
Disposable
interface, which
implicates that the allocated resources need to be disposed manually using the
respective
dispose()
method when a sound instance is no longer needed, as shown
in the following code snippet:
sound.dispose(); // free allocated memory
Calling the
play()
method of a sound instance will start the playback of its audio
data and will return an ID that is associated with the sound that is being played. A
sound ID can be used to refer to a specific playing sound. This allows you to control
sounds at a later time, such as stopping the playback and changing the volume,
pitch, and pan.