Chapter 21 Unit Testing and Audio Playback
Playing Sounds
BeatBox also needs to be able to play sounds. Add the play(Sound) method to BeatBox.
Listing 21.5 Playing sounds back (BeatBox.java)
public BeatBox(Context context) {
mAssets = context.getAssets();
// This old constructor is deprecated but needed for compatibility
mSoundPool = new SoundPool(MAX_SOUNDS, AudioManager.STREAM_MUSIC, 0);
loadSounds();
}
public void play(Sound sound) {
Integer soundId = sound.getSoundId();
if (soundId == null) {
return;
}
mSoundPool.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f);
}
private void loadSounds() {
Before playing your soundId, you check to make sure it is not null. This might happen if the Sound
failed to load.
Once you are sure you have a non-null value, you play the sound by calling SoundPool.play(int,
float, float, int, int, float). Those parameters are, respectively: the sound ID, volume on the
left, volume on the right, priority (which is ignored), whether the audio should loop, and playback rate.
For full volume and normal playback rate, you pass in 1.0. Passing in 0 for the looping value says “do
not loop.” (You can pass in -1 if you want it to loop forever. We speculate that this would be incredibly
annoying.)
With that method written, you are now ready to integrate sound playback into SoundViewModel. You
will perform this integration in a test-first manner – that is, you will first write a failing unit test and
then implement the integration to make the test pass.
Test Dependencies
Before you write your test, you will need to add a couple of tools to your testing environment: Mockito
and Hamcrest. Mockito is a Java framework that makes it easy to create simple mock objects. These
mock objects will help you isolate your tests of SoundViewModel so that you do not accidentally test
other objects at the same time.
Hamcrest, on the other hand, is a library of matchers. Matchers are tools that make it easy to “match”
conditions in your code and fail if your code does not match what you expect. You will use them to
verify that your code works as you expect it to.
You only need these two libraries in your test builds, so you will add them as test dependencies. Start
by right-clicking your app module and selecting Open Module Settings.