0

I'm using SoundPool to play sounds in an arcade game I am creating. However the playPassSound() takes around 40ms from start to finish. I only construct 1x SoundPlayer that loads all of the sounds only once. I am calling playPassSound() within my game thread that also deals with the render calls.

This is what my SoundPlayer class looks like(just an encapsulation of everything related to 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;
}

}

Why does playPassSound()take so long? How can I decouple it from my game/render thread so that the gameplay is unaffected by it?

1 Answers1

0

Just use Mediaplayer instead... Don't bother debugging this. There doesn't seem to be any real solution to this problem out there. Only this hack.

Community
  • 1
  • 1