A (175)

(Tuis.) #1

466 CHAPTER 12: Digital Audio: Providing Aural Feedback for UI Designs Using SoundPool


What we are going to do is to put a buttonSamples.load( ) method call inside a
buttonSampleArray.append( ) method call. This .append( ) method call will add (append) SoundPool
objects to a SparseIntArray object and will specify their order within that Array. The .load( ) method
call will load your SoundPool object with the digital audio sample reference along with the
Context object for MainActivity and finally the sound priority.


The Java programming constructs for loading the SparseIntArray object with three SoundPool
objects, while at the same time loading the SoundPool object with the three audio assets which you
just copied into the /res/raw folder, should look like the following Java programming structure, which
is also shown in Figure 12-19:


buttonSampleArray.append(1, buttonSamples.load(this, R.raw.buttonaudio, 1));
buttonSampleArray.append(2, buttonSamples.load(this, R.raw.buttonaudio2, 1));
buttonSampleArray.append(3, buttonSamples.load(this, R.raw.buttonaudio3, 1));


Now that your SoundPool engine is declared, instantiated, and set up for use, we need to create
another method, which will “trigger” the SoundPool engine when one of your ImageButton UI
elements is clicked. We will call this method .triggerSample( ), and this method will contain all of
the AudioManager methods and SoundPool methods which will be needed to play the correct
(selected) sample back out of the SoundPool engine using the volume the user has set for their
Android device.


Creating a .triggerSample() Method: SoundPool .play()


The first step in creating the .triggerSample( ) method is to close up the other six methods in your
MainActivity class, using the minus - icons at the left side of the Eclipse editing pane. Then, add a
public void triggerSample method with parameters for sound and pitch, using the following line of
Java code, as shown in Figure 12-20:


public void triggerSample (int sound, float pitch) { method code will go in here }


Figure 12-19. Load buttonSampleArray with three references to buttonSamples objects while also loading them

Free download pdf