Creating a SoundPool

Your first job is to build out sound playback inside BeatBox. To do that, first create a SoundPool object (Listing 20.1).

Listing 20.1  Creating a SoundPool (BeatBox.kt)

private const val TAG = "BeatBox"
private const val SOUNDS_FOLDER = "sample_sounds"
private const val MAX_SOUNDS = 5

class BeatBox(private val assets: AssetManager) {

    val sounds: List<Sound>
    private val soundPool = SoundPool.Builder()
        .setMaxStreams(MAX_SOUNDS)
        .build()

    init {
        sounds = loadSounds()
    }
    ...
}

A Builder is used to create a SoundPool instance. The setMaxStreams(Int) option on the builder 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.

In addition to the max streams option, the SoundPool builder allows you to specify different attributes of the audio stream with the setAudioAttributes(AudioAttributes) option. Check the documentation for more information on what this does. The default audio attributes work well enough in this example, so you can leave this option out for now.

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

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