21. Unit Testing and Audio Playback
One reason MVVM architecture is so appealing is that it makes a critical programming practice easier:
unit testing. Unit testing is the practice of writing small programs that verify the standalone behavior of
each unit of your main app. Because BeatBox’s units are each classes, classes are what your unit tests
will test.
In this chapter, you will finally play all of the .wav files you loaded in the previous chapter. As you
build and integrate sound playback, you will write unit tests for your SoundViewModel’s integration
with BeatBox.
Android’s audio APIs are low level for the most part, but there is a tool practically tailor-made for the
app you are writing: SoundPool. SoundPool can load a large set of sounds into memory and control the
maximum number of sounds that are playing back at any one time. So, if your app’s user gets a bit too
excited and mashes all the buttons at the same time, it will not break your app or overtax your phone.
Ready? Time to get started.
Creating a SoundPool
Your first job is to build out sound playback inside BeatBox. To do that, first create a SoundPool object.
Listing 21.1 Creating a SoundPool (BeatBox.java)
public class BeatBox {
private static final String TAG = "BeatBox";
private static final String SOUNDS_FOLDER = "sample_sounds";
private static final int MAX_SOUNDS = 5;
private AssetManager mAssets;
private List
private SoundPool mSoundPool;
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();
}
...
}