i am trying to develop a android app for playing a video from raw folder. am using custom control options. the getduration() returns -1 so i cant set max value to my seekbar. here is my code
private MediaController mediaController;
private VideoView videoView;
public TextView duration;
private int timeElapsed=0,finalTime=0;
private int forwardTime=2000, backwardTime=2000;
private SeekBar seekBar;
private Handler durationHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
}
public void initialize()
{
videoView =(VideoView)findViewById(R.id.videoView1);
mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
String
uri1="android.resource://"+getPackageName()+"/"+R.raw.materialdesign;
Uri uri = Uri.parse(uri1);
videoView.setMediaController(null);
videoView.setVideoPath("android.resource://" + getPackageName() + "/" +
R.raw.materialdesign);
Log.e("finalTime", "" + finalTime);
finalTime = videoView.getDuration();
Log.e("finalTime", ""+finalTime);
Log.e("finalTime", ""+videoView.getDuration());
duration = (TextView) findViewById(R.id.songDuration);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setMax(finalTime);
seekBar.setClickable(false);
videoView.requestFocus();
}
In case you haven't found a solution, VideoView.getDuration()
will return -1 if the video is not in playback state. The video is not in playback state until it has been prepared. So calling VideoView.getDuration()
directly after setting the URI does not guarantee that the video has been prepared.
I found this by looking at the source of VideoView:
@Override
public int getDuration() {
if (isInPlaybackState()) {
return mMediaPlayer.getDuration();
}
return -1;
}
The solution is to set an OnPreparedListener to your VideoView, and obtain the duration once the video is prepared. You can then use VideoView.getDuration()
or MediaPlayer.getDuration()
, which are nearly identical.
Solution:
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
int duration = mp.getDuration();
int videoDuration = videoView.getDuration();
Log.d(TAG, String.format("onPrepared: duration=%d, videoDuration=%d", duration,
videoDuration);
}
seekBar.setMax(videoDuration);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With