Search code examples
androidmedia-player

Pause/Stop MediaPlayer Android at given time programmatically


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


Solution

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