Game Development Reference
In-Depth Information
// Play from cache
mSounds.get(key).play();
}
else {
// load clip from disk
AudioClip clip = new AudioClip(mContext, id);
clip.play();
// cache sound
mSounds.put(key, clip);
mClipCount++;
}
Listing 6-12 shows how it is done. Furthermore, AudioManager also implements several methods.
First, getInstance() is a singleton method used to provide only one instance of AudioManager .
preloadSounds(Context ctx) preloads commonly used sounds. An application context is required
for the inner AudioClip class, which is used to wrap the Android media player. The next fragment shows
how this method uses the resource IDs of the most common sounds to load them into memory. The goal
of this method is to improve performance by keeping these sounds in memory at all times:
public void preloadSounds(Context ctx) {
int[] IDS = new int[] { R.raw.doropn, R.raw.dorcls,
R.raw.pistol, R.raw.wpnup };
// Preload sound WAVs using their IDs
Resources res = mContext.getResources();
for (int i = 0; i < IDS.length; i++) {
final int id = IDS[i];
final String key = res.getResourceName(id);
Log.d(TAG, "PreLoading sound " + key + " ID " + id);
mSounds.put(key, new AudioClip(ctx, id));
}
}
Next, startMusic(Context ctx, int midx) starts the background music given a native music ID.
Note that there is only one audio clip for music. This means only one music track can be played at a
time. An Android context is required for the AudioClip :
public void startMusic(Context ctx, int midx) {
// Obtain a the raw music ID from the SoundNames mapping class
int id = SoundNames.Music[midx];
if (id == 0)
return;
try {
// Check if the RESOURCE exists on disk
mContext.getResources().getResourceName(id);
Search WWH ::




Custom Search