Java 同时播放声音
我正在Android上创建一个游戏,我已经把这个问题推迟了一段时间,现在我又回到这个问题上来了。在我的游戏中,我有背景节拍,枪声,爆炸声。。。等等,我需要能够同时播放它们。现在,当我在SoundPool类上调用play时,当前播放的声音被中断,新的声音开始播放。下面是我的SoundManager类以及用法。任何帮助都将不胜感激,因为这是我第一个需要这么多音效的游戏。谢谢Java 同时播放声音,java,android,audio,Java,Android,Audio,我正在Android上创建一个游戏,我已经把这个问题推迟了一段时间,现在我又回到这个问题上来了。在我的游戏中,我有背景节拍,枪声,爆炸声。。。等等,我需要能够同时播放它们。现在,当我在SoundPool类上调用play时,当前播放的声音被中断,新的声音开始播放。下面是我的SoundManager类以及用法。任何帮助都将不胜感激,因为这是我第一个需要这么多音效的游戏。谢谢 public class SoundManager { private SoundPool mSoundPool; priv
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);
}
}
。。。因此,使用这种风格,我在加载时将所有声音添加到声音池,然后根据用户输入,我只想播放声音。这看起来对吗?或者我应该试着用另一种方式来解决这个问题吗?好吧,我最终还是弄明白了,以防其他人想知道。问题不在于它不能一次播放多个声音,而在于它一次只能播放4个声音,这给我的印象是声音在停止和开始。在该行的构造函数中
mSoundPool=newsoundpool(4,AudioManager.STREAM_MUSIC,0);
需要更改以允许更多流同时播放。因此,通过将第一个参数从4改为20,可以同时播放20种声音。游戏现在听起来好多了哈哈。希望这对其他人有所帮助。我可以问一下,您在代码中使用流音乐和流铃声的原因是什么吗?这是一个特殊的用例吗?
SoundManager sm = new SoundManager(this);
sm.addSound(0, R.raw.explosion);
sm.playSound(0);