Two ways for Android beginners to obtain network/local video duration

the first way

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) {
    
    
}

结果:
insert image description here

the second way

VideoView.getDuration()

Obtaining the total duration of the video in this way requires the video to enter a playable state, otherwise it will return -1, but it is not required in the first way.
For detailed answers, refer to the following answer:

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);
});

Guess you like

Origin blog.csdn.net/qq_41359651/article/details/119719359