462 CHAPTER 12: Digital Audio: Providing Aural Feedback for UI Designs Using SoundPool
In the case where the sample priority for the new stream is lower than all the active streams, the new
sound will not play, and the .play( ) function will return a streamID of zero. For this reason, be sure
that your application’s Java code keeps track of exactly what is going on with your audio sample
priority level settings.
Samples are looped in SoundPool by setting any non-zero looping value. The exception to this is
that a value of -1 will cause samples to loop forever, and under this circumstance, the application
code must make a call to the SoundPool .stop( ) method to stop the looping sample. So a non-zero
integer value will cause a sample to repeat itself that specified number of times; thus, a value of 7
will cause your sample to play back a total of 8 times, as computers start counting using the number
0 instead of 1.
You can change each sample playback rate using SoundPool, which as mentioned makes this class
into an audio synthesis tool. A sample playback rate equal to 1.0 will cause your sample to play back
at its original frequency. A sample playback rate of 2.0 will cause the sample to be played at twice its
original frequency, which will shift it up a full octave higher, if it is a musical instrument note. Similarly,
a sample playback rate set to 0.5 will cause SoundPool to play that sample at half of its original
frequency, which will sound like it is a full octave lower.
The sample playback rate range of SoundPool is currently limited to 0.5 to 2.0; however, this could
be upgraded in a future API revision to, say, 0.25 to 4, which would give developers a four octave
sample playback range.
Now it’s time to learn how to implement a SoundPool engine, and learn about a couple of other
Android utility classes which are used with SoundPool. As you can see, I’m trying to cover as many
key Android classes in this book as is humanly possible!
Adding a SoundPool Engine to the HelloUniverse
Now it is time to get into Java programming in your MainActivity.java Activity subclass and add a
SoundPool engine so that you can add different aural feedback sounds to your three ImageButton
UI elements.
Open Eclipse, open MainActivity.java in an editing tab, and declare a SoundPool object at the top
of your class. Name it buttonSamples using the following Java object declaration statement,
as shown at the top of Figure 12-15:
SoundPool buttonSamples;