Unloading Sounds

The app works, but to be a good citizen you should clean up your SoundPool by calling SoundPool.release() when you are done with it (Listing 20.18).

Listing 20.18  Releasing your SoundPool (BeatBox.kt)

class BeatBox(private val assets: AssetManager) {
    ...
    fun play(sound: Sound) {
        ...
    }

    fun release() {
        soundPool.release()
    }

    private fun loadSounds(): List<Sound> {
        ...
    }
    ...
}

Then, add a matching BeatBox.release() function in MainActivity (Listing 20.19).

Listing 20.19  Releasing your BeatBox (MainActivity.kt)

class MainActivity : AppCompatActivity() {

    private lateinit var beatBox: BeatBox

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
    }

    override fun onDestroy() {
        super.onDestroy()
        beatBox.release() ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.