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

(gtxtreme123) #1

Chapter 21  Unit Testing and Audio Playback


Lollipop introduced a new way of creating a SoundPool using a SoundPool.Builder. However,
SoundPool.Builder is not available on your minimum-supported API (19), so you are using the older
SoundPool(int, int, int) constructor instead.


The first parameter specifies how many sounds can play at any given time. Here, you pass in 5. If five
sounds are playing and you try to play a sixth one, the SoundPool will stop playing the oldest one.


The second parameter determines the kind of audio stream your SoundPool will play on. Android has
a variety of different audio streams, each of which has its own independent volume settings. This is
why turning down the music does not also turn down your alarms. Check out the documentation for the
AUDIO_* constants in AudioManager to see the other options. STREAM_MUSIC will put you on the same
volume setting as music and games on the device.


And the last parameter? It specifies the quality for the sample rate converter. The documentation says it
is ignored, so you just pass in 0.


Loading Sounds


The next thing to do with your SoundPool is to load it up with sounds. The main benefit of using a
SoundPool over some other methods of playing audio is that SoundPool responds quickly: When you
tell it to play a sound, it will play the sound immediately, with no lag.


The trade-off for that is that you must load sounds into your SoundPool before you play them. Each
sound you load will get its own integer ID. To track this ID, add an mSoundId field to Sound and a
generated getter and setter to keep track of it.


Listing 21.2  Adding sound ID field (Sound.java)


public class Sound {
private String mAssetPath;
private String mName;
private Integer mSoundId;
...
public String getName() {
return mName;
}


public Integer getSoundId() {
return mSoundId;
}


public void setSoundId(Integer soundId) {
mSoundId = soundId;
}
}


By making mSoundId an Integer instead of an int, you make it possible to say that a Sound has no
value set for mSoundId by assigning it a null value.

Free download pdf