Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1
Loading Sounds

Now to load your sounds. Add a load(Sound) method to BeatBox to load a Sound into your
SoundPool.


Listing 21.3  Loading sounds into SoundPool (BeatBox.java)


private void loadSounds() {
...
}


private void load(Sound sound) throws IOException {
AssetFileDescriptor afd = mAssets.openFd(sound.getAssetPath());
int soundId = mSoundPool.load(afd, 1);
sound.setSoundId(soundId);
}


public List getSounds() {
return mSounds;
}
}


Calling mSoundPool.load(AssetFileDescriptor, int) loads a file into your SoundPool for later
playback. To keep track of the sound and play it back again (or unload it), mSoundPool.load(...)
returns an int ID, which you stash in the mSoundId field you just defined. And since calling
openFd(String) throws IOException, load(Sound) throws IOException, too.


Now load up all your sounds by calling load(Sound) inside BeatBox.loadSounds().


Listing 21.4  Loading up all your sounds (BeatBox.java)


private void loadSounds() {
...
for (String filename : soundNames) {
try {
String assetPath = SOUNDS_FOLDER + "/" + filename;
Sound sound = new Sound(assetPath);
load(sound);
mSounds.add(sound);
} catch (IOException ioe) {
Log.e(TAG, "Could not load sound " + filename, ioe);
}
}
}


Run BeatBox to make sure that all the sounds loaded correctly. If they did not, you will see red
exception logs in Logcat.

Free download pdf