2011-05-10 195 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