Pause/Stop MediaPlayer Android at given time programmatically

后端 未结 5 1942
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-09 12:23

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 s

相关标签:
5条回答
  • 2021-02-09 12:35

    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).

    0 讨论(0)
  • 2021-02-09 12:37

    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.

    0 讨论(0)
  • 2021-02-09 12:41

    You can use CountDownTimer

    new CountDownTimer(30000, 1000) {
    
         public void onTick(long millisUntilFinished) {
    
         }
    
         public void onFinish() {
             mp.stop;
             mp.relese();
         }
      }.start();
    
    0 讨论(0)
  • 2021-02-09 12:41

    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.

    0 讨论(0)
  • 2021-02-09 12:44

    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.

    0 讨论(0)
提交回复
热议问题