如何使用OnCompletion侦听器播放某些音乐? 我想按一个按钮转到另一个播放音乐的活动,然后在音乐播放结束时返回。我已经编写了其他的东西。我只是想弄清楚如何使用OnCompletion监听器?
答案 0 :(得分:48)
您应该在OnCompletionListener
完成音乐播放时应该运行的代码,例如:
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
finish(); // finish current activity
}
});
答案 1 :(得分:6)
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer paramMediaPlayer, int paramInt1,int paramInt2) {
// TODO Auto-generated method stub
//your code if any error occurs while playing even you can show an alert to user
return true;
}
});
mPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
//your code if the file was completely played either show an alert to user or start another activity or file.
//even you can finish you activity here
}
});
答案 2 :(得分:4)
我发现上面的内容是正确的但是我在努力放置代码的位置。 请参阅下文,我将此代码放在我的代码之后开始调整!
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.start(); //Next line is the beginning of where to place the code.
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
Toast.makeText(MainActivity.this, "I'm Finished", Toast.LENGTH_SHORT).show();
}
});
}
});
答案 3 :(得分:0)
这是 kotlin 版本的 setOnCompletionListener :
mediaPlayer.setOnCompletionListener(MediaPlayer.OnCompletionListener { it // this is MediaPlayer type
Log.d(TAG,"setOnCompletionListener OnCompletionListener called")
// do other task
})