Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 225
DoruAdryan Avatar asked Jun 21 '13 09:06

DoruAdryan


3 Answers

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

like image 150
Ken Wolf Avatar answered Oct 22 '22 10:10

Ken Wolf


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.

like image 34
Yakiv Mospan Avatar answered Oct 22 '22 09:10

Yakiv Mospan


You can use CountDownTimer

new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {

     }

     public void onFinish() {
         mp.stop;
         mp.relese();
     }
  }.start();
like image 26
Gunaseelan Avatar answered Oct 22 '22 09:10

Gunaseelan