Pause/Stop MediaPlayer Android at given time progr

2020-06-18 03:13发布

问题:

I researched a little bit, but couldn't find any solutions to this problem: I would like to play a MediaPlayer and pause/stop it at a given time.. (ie: play from second 6 to second 17).

I know that I can set its starting point with seekTo() method, but can I pause/stop it from playing by setting an end point (of course, before reaching the file end limit)?

回答1:

There are different ways you could do this, here's one:

int startFrom = 6000;
int endAt = 11000;

MediaPlayer mp;

Runnable stopPlayerTask = new Runnable(){
    @Override
    public void run() {
        mp.pause();
    }};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mp = MediaPlayer.create(this, R.raw.my_sound_file);  
    mp.seekTo(startFrom);
    mp.start();

    Handler handler = new Handler();
    handler.postDelayed(stopPlayerTask, endAt);
}

The mediaplayer will start playing 6 seconds in and pause it 11 seconds after that (at second 17).



回答2:

I think you can create Timer and call seekTo() directly from its task. Then call stop()/pause() inside of that Timer Task.

Maybe this post will be helpfull for you.

Or you can use handler for this task, like Ken Wolf shows you.

Best wishes.



回答3:

You can use CountDownTimer

new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {

     }

     public void onFinish() {
         mp.stop;
         mp.relese();
     }
  }.start();


回答4:

I know this already has an answer but here is an alternative for anyone wanting to do this efficiently for a video with controls.

I saw a different answer that involved constantly checking the position.

Note that this assumes that you do not need a lot of different portions of one video. Even in that case I suggest to follow the below.

If you only need to play a portion of the video and want it to end somewhere, then why not just use free video editing software and clip the end? You can still start it from anywhere using seekTo() but this way you don't have to waste resources checking for a certain position (video with controls).

If you do not have video player controls the accepted answer will work. But if you do have player controls then it would not since a user could pause and play the video.



回答5:

There's a time difference between videoView.start() and video prepared to play depend on video format, those time difference is probably more than 10 frames.

so the best way to do is to start the timer inside OnPreparedListener to minimise the time difference, or even more to get the current playing duration and set a postDelayed timer at that point.