开发者

Playing sounds simultaneously Android

I am creating a game on Android and I have kind of put this problem off for a while, and am now just coming back to it. In my game I have a background beat, gun sounds, explosions... etc. and I need to be able to play them simultaneously. Right now when I call play on the SoundPool class, the currently playing sound gets interrupted and the new one starts to play. My SoundManager class is below as well as the usage. Any help would be much appreciated as this is really my first game where I have needed this many sound effects. Thanks!

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

... and here i开发者_如何转开发s an example of how I use the class.

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

... So with this style I add all my sounds to the SoundPool on load and then based on user input I just want to play the sound. Does this look correct? Or should I try and go about this a different way?


Well I did end up figuring this out in case anyone else wants to know. The problem wasn't that it couldn't play more than one sound at a time it was that it was only able to play 4 sounds at a time which gave me the impression that sounds were stopping and starting. In the constructor this line

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

needed to be changed to allow more streams to play at the same time. So by changing the first argument from a 4 to say, a 20, you could then play 20 sounds at the same time. The game sounds much better now haha. Hope this helps someone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜