0
我使用SoundPool在我創建的街機遊戲中播放聲音。然而,playPassSound()
從開始到結束需要大約40毫秒。我只構造1x SoundPlayer,它只加載一次所有聲音。我在我的遊戲線程中調用playPassSound()
,該線程也處理渲染調用。SoundPool play()塊渲染
這是我的聲音播放類是什麼樣子(聲音有關的一切只是一個封裝):
public class SoundPlayer {
private AudioAttributes audioAttributes;
private final int SOUND_POOL_MAX = 2;
private AudioManager audioManager;
private SoundPool soundPool;
private int soundIdPass;
private float volume;
private boolean passLoaded;
public SoundPlayer(Context context){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
soundPool = new SoundPool.Builder()
.setAudioAttributes(audioAttributes)
.setMaxStreams(SOUND_POOL_MAX)
.build();
}else {
//SoundPool is deprecated as of API Level 21 (Lollipop)
soundPool = new SoundPool(SOUND_POOL_MAX, AudioManager.STREAM_MUSIC, 0);
}
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
soundIdPass = soundPool.load(context, R.raw.pass, 1);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
if(sampleId == soundIdPass){
passLoaded = true;
}
});
}
public void playPassSound(){
controlVolume();
soundPool.play(soundIdPass, volume, volume, 1, 0, 1f);
}
public void controlVolume(){
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
volume = actualVolume/maxVolume;
}
}
爲什麼playPassSound()
花了這麼長時間?我怎樣才能將它從我的遊戲/渲染線程中分離出來,以便遊戲不受它影響?