同时播放声音 Android

11

我正在开发一款安卓游戏,这个问题已经拖了一段时间,现在回来重视它了。在我的游戏中,有背景音乐、枪声、爆炸等声效,我需要能够同时播放它们。目前,当我在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中,然后根据用户输入,我只想播放声音。这看起来正确吗?还是应该尝试另一种方式?

1个回答

17

如果有其他人想知道,我最终还是解决了这个问题。问题不在于它不能同时播放多个声音,而在于它一次只能播放4个声音,这让我误以为声音正在停止和重新开始。在构造函数中,需要更改以下行:

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

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


请问您在代码中使用STREAM_MUSIC和STREAM_RING的原因是什么?这是一个特殊的用例吗? - Salx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接