Loading Sounds

The next thing to do with your SoundPool is to load it up with sounds. The main benefit of using a SoundPool over some other methods of playing audio is that SoundPool responds quickly: When you tell it to play a sound, it will play the sound immediately, with no lag.

The trade-off for that is that you must load sounds into your SoundPool before you play them. Each sound you load will get its own integer ID. To track this ID, add a soundId property to Sound.

Listing 20.2  Adding a sound ID property (Sound.kt)

class Sound(val assetPath: String, var soundId: Int? = null) {
    val name = assetPath.split("/").last().removeSuffix(WAV)
}

By making soundId a nullable type (Int?), you make it possible to say that a Sound has no value set for soundId by assigning it a null value.

Now to load your sounds. Add a load(Sound) function to BeatBox to load a Sound into your SoundPool.

Listing 20.3  Loading sounds into SoundPool (BeatBox.kt)

class BeatBox(private val assets: AssetManager) {
    ...
    private fun loadSounds(): List<Sound> {
        ...
    }

    private fun load(sound: Sound) {
        val afd: AssetFileDescriptor = assets.openFd(sound.assetPath)
        val soundId = soundPool.load(afd, 1)
        sound.soundId = soundId
    }
}

Calling soundPool.load(AssetFileDescriptor, Int) loads a file into your SoundPool for later playback. To keep track of the sound and play it back again (or unload it), soundPool.load(…) returns an Int ID, which you stash in the soundId field you just defined.

Be aware that since calling openFd(String) can throw IOException, load(Sound) can throw IOException, too. This means you will need to handle that exception any time load(Sound) is called.

Now load up all your sounds by calling load(Sound) inside BeatBox.loadSounds().

Listing 20.4  Loading up all your sounds (BeatBox.kt)

private fun loadSounds(): List<Sound> {
    ...
    val sounds = mutableListOf<Sound>()
    soundNames.forEach { filename ->
        val assetPath = "$SOUNDS_FOLDER/$filename"
        val sound = Sound(assetPath)
        sounds.add(sound)
        try {
            load(sound)
            sounds.add(sound)
        } catch (ioe: IOException) {
            Log.e(TAG, "Cound not load sound $filename", ioe)
        }
    }
    return sounds
}

Run BeatBox to make sure that all the sounds loaded correctly. If they did not, you will see red exception logs in Logcat.

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

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