Advertisement
Montaser_m

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

Feb 17th, 2020
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement