使用flutter_ffmpeg无法获取视频宽高问题求助
问题原因与解决方法
在 flutter_ffmpeg: ^0.4.2 版本中,MediaInformation 类并未将 width 和 height 作为公开的 getter 方法暴露出来,所以直接调用 mediaInfo.width 或 mediaInfo.height 会返回 null。你在调试器中看到的灰色字段,是 getAllProperties() 返回字典里的未映射键值,无法通过类的公开接口直接访问,必须手动从字典中提取。
解决步骤
方法1:从根属性字典直接提取
如果调试中看到 width 和 height 存在于 getAllProperties() 的根节点,可直接取值:
Future<void> getVideoInfo(String videoPath) async { final mediaInfo = await FlutterFFprobe.getMediaInformation(videoPath); final allProps = mediaInfo.getAllProperties(); // 直接从根字典取宽高 final int? width = allProps['width']; final int? height = allProps['height']; final String? duration = mediaInfo.getDuration(); print('时长:$duration,宽高:${width}x${height}'); }
方法2:遍历视频流提取(更通用)
多数情况下,视频的宽高信息会存储在视频流(streams)节点中,而非根属性,这种方式兼容性更强:
Future<void> getVideoInfo(String videoPath) async { final mediaInfo = await FlutterFFprobe.getMediaInformation(videoPath); final allProps = mediaInfo.getAllProperties(); if (allProps.containsKey('streams')) { final List streams = allProps['streams'] as List; // 遍历所有流,找到视频类型的流 for (var stream in streams) { if (stream['codec_type'] == 'video') { final int? width = stream['width']; final int? height = stream['height']; print('视频宽高:${width}x${height}'); break; } } } final String? duration = mediaInfo.getDuration(); print('时长:$duration'); }
补充说明
flutter_ffmpeg: ^0.4.2 是比较老旧的版本,后续版本已经优化了媒体信息的获取接口,若项目允许,建议升级到最新稳定版,能更方便地通过公开 getter 获取宽高信息。
内容的提问来源于stack exchange,提问作者user31929
相关产品推荐
相关产品推荐

