Audio - GameDevWeek/CodeBase GitHub Wiki

GDW-Commons-GDX provides a couple of helpers to allow easier playback of music and sounds:

MusicManager

package de.hochschuletrier.gdw.commons.gdx.audio;

Change Global Volume/Mute

// Set Volume on a scale from 0.0f to 1.0f
MusicManager.setGlobalVolume(0.5f);

// Mute or unmute
MusicManager.setMuted(true);

Playing Music

// Play the next music track, crossfading the previous track with a fading time of 2 seconds
MusicManager.play(assetManager.getMusic("gameplay"), 2.0f);

Stopping Music

// Passing null makes the current track fade out.
MusicManager.play(null, 2.0f);

// Stop music instantly
MusicManager.stop();

Updating MusicManager

// You need to call update every frame so fading gets updated correctly.
MusicManager.update(delta);

SoundEmitter

A sound emitter is like a speaker in your world. It can play multiple sounds at a specified position.

Note that this code uses the OpenAL backend, so don't try to use it with other backends. Also, it does not have any prioritysystem yet, so if you play too many concurrent sounds, the newest ones might not start.

Change Global Volume/Mute

// Set Volume on a scale from 0.0f to 1.0f
SoundEmitter.setGlobalVolume(0.5f);

// Mute or unmute
SoundEmitter.setMuted(true);

Positioning the virtual head

// Mode.MONO can be used if stereo output is not desired.
SoundEmitter.setListenerPosition(x, y, z, SoundEmitter.Mode.STEREO);

World scale

// Make this value smaller if you feel your virtual head is too small.
// i.e. if a sound moving from left ear to right ear has too little cross-fading
SoundEmitter.setWorldScale(1/1000.0f);

How to use a SoundEmitter

Remember, one emitter can play multiple sounds and update their positions. SoundEmitter implements Disposable, so you can recycle them.

// Create a new emitter (usually an attribute of a component)
SoundEmitter emitter = new SoundEmitter();

// Play a sound (the SoundInstance is only needed if you need to modify the played sound after that)
SoundInstance si = emitter.play(assetManager.getSound("explosion"), loop);

// You need to call update every frame so sounds get freed correctly.
emitter.update();

// Change the position of the emitter when needed (updates all sound instances)
emitter.setPosition(x, y, z);

// Dispose the emitters resources when done
emitter.dispose();

The Global Emitter

A global Emitter exists to play sounds directly in the virtual head or at a specified position.

// Play an announcer sound
si = SoundEmitter.playGlobal(sound, loop);

// Play a sound that does not need to update its position in the world
si = SoundEmitter.playGlobal(sound, loop, x, y, z);

//  Update the global emitter
SoundEmitter.updateGlobal();

// Dispose the global emitters resources
SoundEmitter.disposeGlobal();