我目前正在播放一首歌,第一首歌结束后,第二首歌开始播放。当我的第二首歌曲结束时,第三首歌曲应该开始播放,但不是。如何使用MediaPlayer执行此操作。
这是我的onCompletion代码:
@Override
public void onCompletion(MediaPlayer mp) {
didFinishFirst = true;
if(didFinishFirst) {
Uri songUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.two);
mp = MediaPlayer.create(getApplicationContext(), songUri);
mp.start();
mState = STATE_INITIALIZED;
didFinishSecond = true;
} else if(didFinishSecond){
Uri songUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.three);
mp = MediaPlayer.create(getApplicationContext(), songUri);
mp.start();
mState = STATE_INITIALIZED;
didFinishThird = true;
}
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
// No need
}
});
}
最佳答案
您需要再次将完成侦听器链接到MediaPLayer.create
返回的新媒体播放器实例。只有这样oncompletion
才会被触发
Override
public void onCompletion(MediaPlayer mp) {
didFinishFirst = true;
if(didFinishFirst) {
Uri songUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.two);
mp = MediaPlayer.create(getApplicationContext(), songUri);
mp.start();
mState = STATE_INITIALIZED;
didFinishSecond = true;
mp.setOnCompletionListener(this);
// ^^^^^^^^^^^^^^^^^^^^^^
} else if(didFinishSecond){
Uri songUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.three);
mp = MediaPlayer.create(getApplicationContext(), songUri);
mp.start();
mState = STATE_INITIALIZED;
didFinishThird = true;
mp.setOnCompletionListener(this);
// ^^^^^^^^^^^^^^^^^^^^^^
}
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
// No need
}
});
}