SHARE
TWEET

Playing sound FX for a game with android.media.SoundPool..

Montaser_m Feb 17th, 2020 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public static final int SOUND_EXPLOSION = 1;
  2.  
  3. private SoundPool soundPool;
  4. private HashMap<Integer, Integer> soundPoolMap;
  5.  
  6. private void initSounds() {
  7.      soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
  8.      soundPoolMap = new HashMap<Integer, Integer>();
  9.      soundPoolMap.put(SOUND_EXPLOSION,
  10.  soundPool.load(getContext(), R.raw.explosion, 1));
  11. }
  12.          
  13. public void playSound(int sound) {
  14.     /* Updated: The next 4 lines calculate the current volume in a scale of 0.0 to 1.0 */
  15.     AudioManager mgr = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
  16.     float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
  17.     float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);    
  18.     float volume = streamVolumeCurrent / streamVolumeMax;
  19.    
  20.     /* Play the sound with the correct volume */
  21.     soundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0, 1f);    
  22. }
  23.  
  24. public void explode() {
  25.     playSound(SOUND_EXPLOSION);
  26. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top