Recipe Using Sound Resources Efficiently

To keep the smaller memory requirements of compressed audio files but also the benefit of lower-latency playback of raw audio files, the SoundPool class can be used.This uses the MediaPlayer service to decode audio and provides methods to repeat sound buffers and also speed them up or slow them down.

Usage is similar to other sound recipes: initialize, load a resource, play, and release. However, note that the SoundPool launches a background thread, so a play() right after a load() might not produce sound if the resource does not have time to load. Similarly, a release() called right after a play() releases the resource before it can be played.There-fore, it is best to tie SoundPool resources to activity lifecycle events (such as onCreate and onPause) and tie the playback of SoundPool resources to a user-generated event (such as a button press or advancement in a game).

Using the same layout file as in Listing 6.7, the main activity of this recipe is shown in Listing 6.10.A button press triggers the SoundPool to repeat a drum beat eight times (the initial time plus seven repeats).Also, the rate alternates from half-speed to double-speed between button presses. Up to ten streams can play at once, which means ten quick button presses can launch ten drum beats playing simultaneously.

Listing 6.10 src/com/cookbook/audio_ex/ package com.cookbook.audio_ex;

import; import; import;

import android.os.Bundle; import android.view.View; import android.widget.Button;

public class AudioExamplesSP extends Activity { static float rate = 0.5f; ^Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);


Button playDrumButton = (Button) findViewById(;

final SoundPool mySP = new

SoundPool(10, AudioManager.STREAM_MUSIC, 0); final int soundId = mySP.load(this, R.raw.drum_beat, 1);

playDrumButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { rate = 1/rate;

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook

Post a comment