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<Sound> mSounds = new ArrayList<>();
    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();
    }
    ...
}

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.228.88