第一种方式
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4", new HashMap<>());
String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); // 播放时长单位为毫秒
int seconds = 0;
Log.e("TAG", "onCreate: " + mBinding.videoView.getDuration() + " " + duration);
try {
seconds = Integer.parseInt(duration1) / 1000;
} catch (NumberFormatException exception) {
}
结果:
第二种方式
VideoView.getDuration()
通过这种方式获取视频的总时长时需要视频进入能够播放的状态, 否则会返回-1
, 但是通过第一种方式不需要.
详细解答参考下面这个回答:
videoview-getduration-returns-1
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); });