2013-07-12 25 views
1

我嘗試寫一些遊戲,在屏幕上同時顯示10-30個單位。在Android中的許多對象使用SoundPools的最佳方式是什麼?

每個單元都有不同的聲音:

  • 中性
  • 撞到
  • 攻擊

所以我完全有4×30 = 120 wav文件。

當然,它應該是一些調度員,以防止在同一時間播放幾個聲音。

我的問題是:

我需要通過這個類來添加SoundPool到每一個單位對象或創建單獨的類SoundPool singelton和管理所有單位。

我可以嘗試做這兩種選擇,但我擔心它可能會導致內存泄漏和性能。

謝謝

回答

2

使用下面的類來表示你有每個聲音文件。根據需要將它們保留在周圍,並在完成之後處置它們以避免內存泄漏。

public class AndroidSound implements Sound { 
int soundId; 
SoundPool soundPool; 

public AndroidSound(SoundPool soundPool, int soundId) { 
    this.soundId = soundId; 
    this.soundPool = soundPool; 
} 

@Override 
public void play(float volume) { 
    soundPool.play(soundId, volume, volume, 0, 0, 1); 
} 

@Override 
public void dispose() { 
    soundPool.unload(soundId); 
} 

}

使用下面的類newSound方法來獲得一個新的Sound實例,只要你想,你可以發揮和處理。創建你的聲音並將它們存儲在一個集合中,並根據需要使用它們。

public class AndroidAudio implements Audio { 
AssetManager assets; 
SoundPool soundPool; 

public AndroidAudio(Activity activity) { 
    activity.setVolumeControlStream(AudioManager.STREAM_MUSIC); 
    this.assets = activity.getAssets(); 
    this.soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0); 
} 

@Override 
public Music newMusic(String filename) { 
    try { 
     AssetFileDescriptor assetDescriptor = assets.openFd(filename); 
     return new AndroidMusic(assetDescriptor); 
    } catch (IOException e) { 
     throw new RuntimeException("Couldn't load music '" + filename + "'"); 
    } 
} 

@Override 
public Sound newSound(String filename) { 
    try { 
     AssetFileDescriptor assetDescriptor = assets.openFd(filename); 
     int soundId = soundPool.load(assetDescriptor, 0); 
     return new AndroidSound(soundPool, soundId); 
    } catch (IOException e) { 
     throw new RuntimeException("Couldn't load sound '" + filename + "'"); 
    } 
} 
+0

謝謝,我會試試你的方法。它的工作原理是試圖爲幾個對象設置它 –

相關問題