I want to loop a track using MediaPlayer
. I have set the MediaPlayer
object to loop. The problem is the track finishes and goes into next loop, there is a noticeable jitter/lag. How can I avoid that? I currently use the code mentioned in this link. I use the following code to set up my MediaPlayer
instance.
private void setupMPLesson() {
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mMPCurrPlayer = new MediaPlayer();
mMPCurrPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mMPCurrPlayer.setDataSource(this, Uri.parse("android.resource://" + RESOURCES_PACKAGE +
"/" + R.raw.sweep_up_down_wav));
mMPCurrPlayer.prepare();
} catch (IOException e) {
Log.e(TAG, "Could not find the file:", e);
}
// Create the media player instance for the next iteration ...
createNextMediaPlayer();
}
The method createNextMediaPlayer()
is as follows:
private void createNextMediaPlayer() {
mNextPlayer = new MediaPlayer();
mNextPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mNextPlayer.setDataSource(this, Uri.parse("android.resource://" + RESOURCES_PACKAGE +
"/" + R.raw.sweep_up_down_wav));
} catch (IOException e) {
Log.e(TAG,"Could not find the file:", e);
}
mNextPlayer.setOnPreparedListener(this);
mNextPlayer.prepareAsync();
// setting the completion listener to the mMPCurrPlayer
mMPCurrPlayer.setOnCompletionListener(this);
}
Once the mNextPlayer
is prepared, I do the following:
@Override
public void onPrepared(MediaPlayer mp) {
mMPCurrPlayer.setNextMediaPlayer(mNextPlayer);
}
And on completion of a cloop, I implement the OnCompletionListener as:
@Override
public void onCompletion(MediaPlayer mp) {
// Check if the mp completed playing the number of loops required ..
// If the current loop is smaller than the number of set loops ..
mCompletedLoops++;
mp.release();
// Assign the current mMPCurrPlayer to the created mNextPlayer for looping ..
mMPCurrPlayer = mNextPlayer;
// Create the next media player and make it ready for the next iteration ..
createNextMediaPlayer();
if (mCompletedLoops < mNumLoops) {
return;
}
// stop the media player ..
mMPCurrPlayer.pause();
}
I also keep the track of the current loop and stop once I have crossed the required number of loops.