Play Sound Android Example

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
 
public class SoundManager
{
  private SoundPool soundPool;
  private int[] sm;
  Context context;
 
  public SoundManager(Context context) {
    this.context = context;
    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
    sm = new int[2];
    // fill your sounds
    sm[0] = soundPool.load(context, R.raw.my_sound1, 1);
    sm[1] = soundPool.load(context, R.raw.my_sound2, 1);
  }
 
  public final void playSound(int sound) {
      AudioManager mgr = (AudioManager)context.getSystemService(
          Context.AUDIO_SERVICE);  
      float streamVolumeCurrent =
          mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
      float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
      float volume = streamVolumeCurrent / streamVolumeMax;
      soundPool.play(sm[sound], volume, volume, 1, 0, 1f);
  }
 
  public final void cleanUpIfEnd() {
    sm = null;
    context = null;
    soundPool.release();
    soundPool = null;
  }
}
This entry was posted in Android Examples Code and tagged , . Bookmark the permalink.


Comments are closed.



6,208 views