Pause/Stop MediaPlayer Android at given time programmatically

后端 未结 5 1955
佛祖请我去吃肉
佛祖请我去吃肉 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).

提交回复
热议问题