That’s a better way to do it. I would write similar code in a real project.
For the purposes of the book, code like this adds an additional hurdle towards understanding how SoundPool works. In general, we try to write less code so that the reader can understand the core concepts.
I used your code to avoid an error I get when a button is pressed by the user.
Instead of a sound playing I get the following in the logs.
03-24 15:02:12.725 10411-10424/android.bignerdranch.beatbox I/art: Background sticky concurrent mark sweep GC freed 1726(96KB) AllocSpace objects, 0(0B) LOS objects, 9% free, 1819KB/2002KB, paused 42.549ms total 50.207ms
03-24 15:02:12.725 1629-1849/system_process W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
03-24 15:02:12.726 1155-1155/? E/AudioMixer: AudioMixer::getTrackName out of available tracks
03-24 15:02:12.726 1155-1155/? E/AudioFlinger: no more track names available
03-24 15:02:12.726 1155-1155/? E/AudioFlinger: createTrack_l() initCheck failed -12; no control block?
03-24 15:02:12.742 1629-1849/system_process E/AudioTrack: AudioFlinger could not create track, status: -12
03-24 15:02:12.744 1629-1849/system_process E/SoundPool: Error creating AudioTrack
03-24 15:02:12.749 1155-7053/? E/AudioMixer: AudioMixer::getTrackName out of available tracks
03-24 15:02:12.749 1155-7053/? E/AudioFlinger: no more track names available
03-24 15:02:12.749 1155-7053/? E/AudioFlinger: createTrack_l() initCheck failed -12; no control block?
03-24 15:02:12.749 10411-10411/android.bignerdranch.beatbox E/AudioTrack: AudioFlinger could not create track, status: -12
03-24 15:02:12.749 10411-10411/android.bignerdranch.beatbox E/SoundPool: Error creating AudioTrack
I was getting this error for two Lollipop Emulators API 22 for a Nexus 7 tablet and a Nexus One phone.
But when I test it on on my real Huawei P10 with Android 7.0 (Nougat API level 24) it works with the textbook version and also with Ilya’s extra code above. Still looking for answer why the emulators don’t work. But now off to chapter 22 (3rd ed.).