2011-05-10 232 views
10

我在Android上创建了一款游戏,我有一段时间没有解决这个问题,现在我只是想回到它。在我的游戏中,我有背景音乐,枪声,爆炸等等,我需要能够同时播放它们。现在,当我在SoundPool类上调用Play时,当前播放的声音被打断,新的声音开始播放。我的SoundManager类以及用法如下。任何帮助将不胜感激,因为这真的是我的第一场比赛,我需要这么多的音效。谢谢!同时播放声音Android

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负载,然后根据用户输入我只是想播放声音。这看起来是否正确?或者我应该试试这种不同的方式?

回答

15

好吧,我最终确定了这一点,以防其他人想知道的情况。问题不是它一次只能播放一个以上的声音,而是一次只能播放4个声音,这让我觉得声音停止并开始播放。在构造该行

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

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

+1

很高兴知道不要忘记接受你自己的答案! – schwiz 2011-06-27 20:37:30

+0

感谢提醒我! – DRiFTy 2011-06-28 13:30:54

+0

请问您的代码中使用STREAM_MUSIC以及STREAM_RING的理由是什么?这是一个特殊用例吗? – Salx 2011-09-14 21:56:17