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/AudioExamplesSP.java package com.cookbook.audio_ex;

import android.app.Activity; import android.media.AudioManager; import android.media.SoundPool;

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);

setContentView(R.layout.main);

Button playDrumButton = (Button) findViewById(R.id.play_pause);

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;

0 0

Post a comment

  • Receive news updates via email from this site