OnCompletion listener with MediaPlayer

核能气质少年 提交于 2019-12-03 14:42:58

问题


How do i use the OnCompletion listener for some music? I would like to press a button to go to another activity that plays some music and then goes back when the music playback is finished. I allready coded the other stuff. I just cant figure out how to use the OnCompletion listener?


回答1:


You should put the code that should be run when the music is completed in the OnCompletionListener, for example:

mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
        finish(); // finish current activity
    }
});



回答2:


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
}                   
}); 



回答3:


I find that above are correct however I was struggling on where to place the code. See below, i place this code after my code to start the tune!

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();
      }
    });
  }
});


来源:https://stackoverflow.com/questions/9962998/oncompletion-listener-with-mediaplayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!