Game Development Reference
In-Depth Information
Finally, we get an AssetFileDescriptor for the explosion.ogg file we put in the assets/ directory
from the AssetManager . To load the sound, we simply pass that descriptor to the SoundPool.load()
method and store the returned handle. The SoundPool.load() method throws an exception in
case something goes wrong while loading, in which case we catch that and display an error
message.
In the onTouch() method, we simply check whether a finger went up, which indicates that the
screen was tapped. If that's the case and the explosion sound effect was loaded successfully
(indicated by the handle not being -1), we simply play back that sound effect.
When you execute this little activity, simply touch the screen to make the world explode. If you
touch the screen in rapid succession, you'll notice that the sound effect is played multiple times
in an overlapping manner. It would be pretty hard to exceed the 20 playbacks maximum that we
configured into the SoundPool . However, if that happened, one of the currently playing sounds
would just be stopped to make room for the newly requested playback.
Notice that we didn't unload the sound or release the SoundPool in the preceding example. This
is for brevity. Usually you'd release the SoundPool in the onPause() method when the activity is
going to be destroyed. Just remember always to release or unload anything you no longer need.
While the SoundPool class is very easy to use, there are a couple of caveats you should
remember:
ï?® SoundPool.load() method executes the actual loading asynchronously.
This means that you have to wait briefly before you call the SoundPool.play()
method with that sound effect, as the loading might not be finished yet.
Sadly, there's no way to check when the sound effect is done loading.
That's only possible with the SDK version 8 of SoundPool , and we want to
support all Android versions. Usually it's not a big deal, since you will
most likely load other assets as well before the sound effect is played for
the first time.
ï?® SoundPool is known to have problems with MP3 files and long sound files,
where long is defined as “longer than 5 to 6 seconds.� Both problems are
undocumented, so there are no strict rules for deciding whether your sound
effect will be troublesome or not. As a general rule, we'd suggest sticking
to OGG audio files instead of MP3s, and trying for the lowest possible
sampling rate and duration you can get away with before the audio quality
becomes poor.
The
Note As with any API we discuss, there's more functionality in SoundPool . We briefly told you
that you can loop sound effects. For this, you get an ID from the SoundPool.play() method that
you can use to pause or stop a looped sound effect. Check out the SoundPool documentation on
the Android Developers site if you need that functionality.
 
Search WWH ::




Custom Search