使用的是 android.media.SoundPool類
public static final int SOUND_EXPLOSION = 1;
private SoundPool soundPool;
private HashMap<Integer, Integer> soundPoolMap;
private void initSounds() {
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(SOUND_EXPLOSION, soundPool.load(getContext(), R.raw.explosion, 1));//解碼加載explosion,爆炸音
}
/* 播放 */
public void playSound(int sound) {
/* 下面4句計算當前音量,範圍0.0~1.0*/
AudioManager mgr = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;
/* 其當前音量播放聲音 */
soundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0, 1f);
}
/* 播放爆炸音效 */
public void explode() {
playSound(SOUND_EXPLOSION);
}