Playing Sounds

BeatBox also needs to be able to play sounds. Add the play(Sound) function to BeatBox.

Listing 20.5  Playing sounds back (BeatBox.kt)

class BeatBox(private val assets: AssetManager) {
    ...
    init {
        sounds = loadSounds()
    }

    fun play(sound: Sound) {
        sound.soundId?.let {
            soundPool.play(it, 1.0f, 1.0f, 1, 0, 1.0f)
        }
    }
    ...
}

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, 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 function 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.

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

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