1

I set a music file to loop on MediaPlayer for my game, but it causes a 2 sec delay when it loops.

My code:

boolean activateSounds = getIntent().getBooleanExtra("Activate sounds", true);

    if(mp!=null){
        mp.reset();
        mp.release();
    }
    mp = MediaPlayer.create(StartGame.this, R.raw.music1);
    mp.setVolume(8f, 8f);
    mp.setLooping(true); // This is causing delays
    if (activateSounds) mp.start();

For a game, this is not interesting. Is there a way to make MediaPlayer run out of loop delays?

LukeHxH
  • 32
  • 5

1 Answers1

2

I was not able to make setLooping work without a gap.

Only solution that worked for me was to use setNextMediaPlayer call (which is able to start next loop without a gap) and two MediaPlayers.

'pseudo' code:

class Abc implements MediaPlayer.OnCompletionListener {

private final MediaPlayer[] mps = new MediaPlayer[2];

public Abc() {
    mps[0] = new MediaPlayer();
    mps[1] = new MediaPlayer();
    mps[0].setOnCompletionListener(this);
    mps[1].setOnCompletionListener(this);
}

public void start()
    initMediaPlayer(mps[0]);
    initMediaPlayer(mps[1]);

    mps[0].setNextMediaPlayer(mps[1]);
    mps[0].start();
}

private void initMediaPlayer(MediaPlayer mp)
{
    if (mp.isPlaying()){
            mp.stop();
    }
    mp.reset();

    final float volume = 0.07f;

    mp.setDataSource(MY_SOURCE);
    mp.setVolume(volume, volume);
    mp.setLooping(false);

    try {
        mp.prepare();
    }catch(Exception error){
        Log.d("BackgroundMusic", error.toString());
    }
}

@Override
public void onCompletion(MediaPlayer mp)
{
    MediaPlayer cur = mps[0] == mp ? mps[1] : mps[0];

    initMediaPlayer(mp);
    cur.setNextMediaPlayer(mp);
}

}