Android VideoView 持续时间 -1

Android VideoView with duration -1

我正在为VideoView自己创建一个控制器(我知道使用Controller更容易,但这是学校的作业),所以应用程序外观如下(VideoViewSeekBar 和 3 Buttons)

onCreate方法中我写了这段代码

VideoView vwVideo = (VideoView) findViewById(R.id.videoView);
vwVideo.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.baby);

SeekBar skbPosition = (SeekBar) findViewById(R.id.seekBarVideo);
skbPosition.setMax(vwVideo.getDuration());

但是getDuration() returns -1,可能是因为视频还没有加载(*.mp4, 4.47 MB​​, 00:01:44),所以我决定设置单击按钮 "Play" 时 SeekBar 的最大值,但我不知道这是否是解决问题的最佳方法。

有没有更好的解决方案?

如果您想获取视频的持续时间,可以使用 MediaMetadataRetriever 来实现。

MediaMetadataRetriever retriever = new MediaMetadataRetriever();
//use setDataSource() functions to set your data source
retriever.setDataSource(context, Uri.fromFile(videoFile));
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long timeInMillisec = Long.parseLong(time);

如果有任何问题,请更新我。