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

Get Android Programming: The Big Nerd Ranch Guide, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.