gpt4 book ai didi

java - 同时播放声音 Android

转载 作者:搜寻专家 更新时间:2023-10-30 21:24:27 24 4
gpt4 key购买 nike

我正在 Android 上开发一款游戏,我把这个问题搁置了一段时间,现在又要回来处理它了。在我的游戏中,我有背景节拍、枪声、爆炸声……等等,我需要能够同时播放它们。现在,当我在 SoundPool 类上调用 play 时,当前播放的声音会被打断,新的声音开始播放。下面是我的 SoundManager 类以及用法。任何帮助将不胜感激,因为这确实是我的第一款需要这么多音效的游戏。谢谢!

public class SoundManager {
private SoundPool mSoundPool;
private HashMap<Integer, Integer> mSoundPoolMap;
private AudioManager mAudioManager;
private Context mContext;

public SoundManager(Context theContext) {
mContext = theContext;
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer, Integer>();
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
}

public void addSound(int index, int SoundID) {
mSoundPoolMap.put(index, mSoundPool.load(mContext, SoundID, 1));
}

public void playSound(int index) {
float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_RING);
streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_RING);

mSoundPool.play((Integer) mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
}

public void playLoopedSound(int index) {
float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

mSoundPool.play((Integer) mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f);
}
}

...这是我如何使用该类的示例。

SoundManager sm = new SoundManager(this);
sm.addSound(0, R.raw.explosion);
sm.playSound(0);

... 因此,通过这种风格,我在加载时将所有声音添加到 SoundPool,然后根据用户输入我只想播放声音。这看起来正确吗?还是我应该尝试以不同的方式解决这个问题?

最佳答案

好吧,我确实最终弄清楚了这一点,以防其他人想知道。问题不在于它一次不能播放多个声音,而是它一次只能播放 4 种声音,这给我的印象是声音时断时续。在构造函数中这一行


mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);

需要更改以允许同时播放更多流。因此,通过将第一个参数从 4 更改为 20,您就可以同时播放 20 个声音。现在游戏听起来好多了哈哈。希望这对某人有帮助。

关于java - 同时播放声音 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5957444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com