Android平台游戏声音播放实践

本文介绍了一种在游戏中高效加载和播放音效的方法。通过使用SoundPool类仅加载一次音频文件,实现多次调用播放的功能,同时根据系统音量动态调整播放音量,确保音效在不同场景下的一致性和沉浸感。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大部分游戏都有音效,不然游戏乐趣会降低很多,而几乎所有音效都是重复播放的。

下面的代码只加载一次音频文件,但是却可以被多次使用。请将音频文件放置在/res/raw路径中。

 

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));

}

 

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);

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值