如何解决从 FileDescriptor 或 ParcelFileDescriptor 获取视频时长
我一直在使用这种类型的代码来获取我的 Android 设备上的视频时长:
int dataColumn = cursor
.getColumnIndex(MediaStore.Files.FileColumns.DATA);
String path = cursor.getString(dataColumn);
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
File file = new File(path);
retriever.setDataSource(context,Uri.fromFile(file));
boolean hasVideo = retriever.extractMetadata(MediaMetadataRetriever.MetaDATA_KEY_HAS_VIDEO).equals("yes");
String time = retriever.extractMetadata(MediaMetadataRetriever.MetaDATA_KEY_DURATION);
int duration = 0;
if (time != null && hasVideo) {
duration = (int) Math.ceil(Integer.parseInt(time) / 1000);
}
这一直有效,直到我开始在我的应用中定位 Android 11(API 级别 30)。现在持续时间总是报告为 0
。我可以看到 MediaStore.Files.FileColumns.DATA
是 deprecated beginning with Android 10 (API level 29),而 ContentResolver.openFileDescriptor
是推荐的替代方案。但是,我不知道如何从 ParcelFileDescriptor
或 FileDescriptor
获取视频的持续时间。我也无法找到演示如何执行此操作的资源。那么,我该怎么做?
我还尝试了其他可能的解决方案,但都没有奏效:
- 使用
retriever.setDataSource(file.getAbsolutePath())
而不是retriever.setDataSource(context,Uri.fromFile(file))
。我看到了 here 和 here,所以我试了一下,但是没有用(持续时间仍然为零) - 我尝试直接从
MediaStore
查询持续时间字段,但仍然无效。这是我使用的代码:
int vidDurationColumn = cursor.getColumnIndex(MediaStore.Video.Media.DURATION);
int duration = (int)cursor.getInt(vidDurationColumn);
是的,我愿意接受任何可行的想法。谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。