Sound Effect

package com.schnee.basics;

import java.io.IOException;

import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.AssetFileDescriptor;
import android.media.SoundPool;
import android.media.AudioManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

final public class SoundPoolTest extends Activity
{
  SoundPool soundPool;
  int explosionId = -1;

  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    TextView textView = new TextView(this);
    textView.setOnTouchListener(new TextView.OnTouchListener(){
      @Override
      public boolean onTouch(View view, MotionEvent event){
        if(event.getAction() == MotionEvent.ACTION_UP && explosionId != -1)
          soundPool.play(explosionId, 1.0f, 1.0f, 0, 0, 1);
        return true;
      }
    });
    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("Couln't load sound effect from asset." + e.getMessage());
    }
  }
  @Override
  protected void onPause(){
    super.onPause();
    if(explosionId != -1)
      soundPool.unload(explosionId);
    soundPool.release();
  }
}

Remove all ads