Android初学 获取网络/本地视频时长的两种方式

第一种方式

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);
});
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值