Game Development Reference
In-Depth Information
sound effect assigned to it by the SoundPool . Again, we catch any IOException and rethrow it as
an unchecked RuntimeException .
Note We do not release the SoundPool in any of the methods. The reason for this is that
there will always be a single Game instance holding a single Audio instance that holds a single
SoundPool instance. The SoundPool instance will, thus, be alive as long as the activity (and with
it our game) is alive. It will be destroyed automatically as soon as the activity ends.
Next, we will discuss the AndroidSound class, which implements the Sound interface. Listing 5-3
presents its implementation.
Listing 5-3. Implementing the Sound Interface Using AndroidSound.java
package com.badlogic.androidgames.framework.impl;
import android.media.SoundPool;
import com.badlogic.androidgames.framework.Sound;
public class AndroidSound implements Sound {
int soundId;
SoundPool soundPool;
public AndroidSound(SoundPool soundPool, int soundId) {
this .soundId=soundId;
this .soundPool=soundPool;
}
public void play( float volume) {
soundPool.play(soundId, volume, volume, 0, 0, 1);
}
public void dispose() {
soundPool.unload(soundId);
}
}
There are no surprises here. Via the play() and dispose() methods, we simply store the
SoundPool and the ID of the loaded sound effect for later playback and disposal. It doesn't get
any easier than this, thanks to the Android API.
Finally, we have to implement the AndroidMusic class returned by AndroidAudio.newMusic() .
Listing 5-4 shows that class's code, which looks a little more complex than before. This is due
to the state machine that the MediaPlayer uses, which will continuously throw exceptions if we
call methods in certain states. Note that the listing is broken up again, with commentary inserted
where appropriate.
 
Search WWH ::




Custom Search