A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© y1787257661 中级黑马   /  2015-1-5 10:35  /  1162 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

大部分游戏都有音效,不然游戏乐趣会降低很多,而几乎所有音效都是重复播放的。
下面的代码只加载一次音频文件,但是却可以被多次使用。请将音频文件放置在/res/raw路径中。

public static final int SOUND_EXPLOSION = 1;
private SoundPool soundPool;
private HashMap soundPoolMap;

private void initSounds() {
     soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
     soundPoolMap = new HashMap();
     soundPoolMap.put(SOUND_EXPLOSION, soundPool.load(getContext(), R.raw.explosion, 1));
}

public void playSound(int sound) {
   
    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);
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马