我想使用MediaPlayer
循环播放曲目。我已将MediaPlayer
对象设置为循环。问题是轨道完成并进入下一个循环,有明显的抖动/滞后。我怎么能避免这种情况?我目前使用this链接中提到的代码。我使用以下代码设置我的MediaPlayer
实例。
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();
}
方法createNextMediaPlayer()
如下:
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);
}
准备好mNextPlayer
后,我会执行以下操作:
@Override
public void onPrepared(MediaPlayer mp) {
mMPCurrPlayer.setNextMediaPlayer(mNextPlayer);
}
完成一个cloop后,我将OnCompletionListener实现为:
@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();
}
我还跟踪当前循环并在我越过所需数量的循环后停止。