我正在使用SoundPool在我正在创建的街机游戏中播放声音。但是playPassSound()
从开始到结束需要大约40毫秒。我只构造1x SoundPlayer,只加载一次所有声音。我在我的游戏线程中调用playPassSound()
,它也处理渲染调用。
这就是我的SoundPlayer类的样子(只是封装了与Sound相关的所有内容):
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()
需要这么长时间?如何将其与我的游戏/渲染线程分离,以便游戏玩法不受其影响?