Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MediaPlayer.seekTo() not seeking to position on Android

I'm working on an app in which the video is paused at 3 different intervals. After the second pause, if a button is clicked, it should start back from the previous location.

Eg. if it is currently paused at 1:30, then on click of a button, it goes to the previous bookmark, i.e. 00:45.

I thought using MediaPlayer.seekTo() will help me achieve this. But, seekTo() doesn't seek the position at all. The currentPosition stays the same even after a call to seekTo();

Here's my code.

mediaPlayer.setOnSeekCompleteListener(new OnSeekCompleteListener() {
    @Override
    public void onSeekComplete(MediaPlayer mp) {
        Log.d("VID_PLAYER","Seek Complete. Current Position: " + mp.getCurrentPosition());
        mp.start();
    }
});

and somewhere below, I have this...

mediaPlayer.seekTo(45000);

What is the problem? Why isn't seekTo(); working? Any help would be appreciated.

I am currently testing it on Android v4.0.3 (ICS)

like image 341
varun1505 Avatar asked Apr 18 '13 07:04

varun1505


2 Answers

One of the reasons why Android is not able to do seekTo is because of strange encoding of the videos. For example in MP4 format so called "seek points" (i.e. search index) can be specified at the begining and at the end of the file. If they are specified at the begining of the file then seekTo will behave correctly. But if they are specified at the end of the file then seekTo will do nothing and video will start from the begining after seekTo.

This is confirmed bug-or-feature in Android 4.4.2.

P.S. On Youtube all videos are encoded with "seek points" at the begining of the file. So if you have this problem with seekTo in your app first of all check your app with some video files from Youtube. Perhaps you'll need to reencode your videos...

like image 149
Vadim Guzev Avatar answered Nov 14 '22 22:11

Vadim Guzev


Try the code snippet given below to achieve more accuracy in seeking to specific positions of the media.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
    mediaPlayer.seekTo(seekPosition,MediaPlayer.SEEK_CLOSEST);
else 
    mediaPlayer.seekTo((int)seekPosition);

Keep in mind that - as the accuracy increases, speed of seeking decreases. So while playing high resolution videos its advised not to use MediaPlayer.SEEK_CLOSESTmore often.

like image 26
Febin Mathew Avatar answered Nov 14 '22 21:11

Febin Mathew