Game Development Reference
In-Depth Information
import android.media.SoundPool;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
public class SoundPoolTest extends Activity implements OnTouchListener {
SoundPool soundPool;
int explosionId = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
TextView textView = new TextView( this );
textView.setOnTouchListener( this );
setContentView(textView);
setVolumeControlStream(AudioManager. STREAM_MUSIC );
soundPool = new SoundPool(20, AudioManager. STREAM_MUSIC , 0);
try {
AssetManager assetManager = getAssets();
AssetFileDescriptor descriptor = assetManager
.openFd("explosion.ogg");
explosionId = soundPool.load(descriptor, 1);
} catch (IOException e) {
textView.setText("Couldn't load sound effect from asset, "
+ e.getMessage());
}
}
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent. ACTION_UP ) {
if (explosionId != -1) {
soundPool.play(explosionId, 1, 1, 0, 0, 1);
}
}
return true;
}
}
We start off by deriving our class from Activity and letting it implement the OnTouchListener
interface so that we can later process taps on the screen. Our class has two members: the
SoundPool , and the handle to the sound effect we are going to load and play back. We set that to
-1 initially, indicating that the sound effect has not yet been loaded.
In the onCreate() method, we do what we've done a couple of times before: create a TextView ,
register the activity as an OnTouchListener , and set the TextView as the content view.
The next line sets the volume controls to control the music stream, as discussed before. We then
create the SoundPool , and configure it so it can play 20 concurrent effects at once. That should
suffice for the majority of games.
Search WWH ::




Custom Search