如何通过编程获取MP4元数据中的Description字段(macOS环境)
提取MP4文件Description元数据的两种方法
方法一:用mdls命令快速提取
macOS自带的mdls命令可以直接读取系统索引的文件元数据,MP4的Description字段对应键名为kMDItemDescription。
打开「终端」,执行以下命令(替换/path/to/your/file.mp4为你的文件实际路径):
mdls -name kMDItemDescription /path/to/your/file.mp4
执行后会输出键名和对应内容,要是字段为空就显示(null)。
如果只想获取纯内容,去掉键名,用这个命令:
mdls -raw -name kMDItemDescription /path/to/your/file.mp4
方法二:用AppleScript实现(可集成到Automator做右键快捷操作)
如果想要可视化操作,或者做成右键快速提取功能,用AppleScript更方便,它既可以调用系统元数据接口,也能直接调用mdls命令。
基础AppleScript代码(手动选文件)
set targetFile to choose file with prompt "选择要提取Description的MP4文件" of type {"MP4"} set filePath to POSIX path of targetFile set descText to do shell script "mdls -raw -name kMDItemDescription " & quoted form of filePath if descText is not "(null)" then display dialog "文件Description内容:" & linefeed & descText buttons {"复制到剪贴板", "取消"} default button 1 if button returned of result is "复制到剪贴板" then set the clipboard to descText end if else display dialog "该文件的Description字段为空" buttons {"确定"} default button 1 end if
集成到Automator做右键快速操作
- 打开Automator,新建「快速操作」
- 设置「工作流收到」为「文件或文件夹」,运行位置选「访达」
- 添加「运行AppleScript」动作,把默认代码替换成下面的版本(支持处理选中的多个MP4文件):
on run {input, parameters} set resultText to "" repeat with aFile in input set filePath to POSIX path of aFile set fileName to name of (info for aFile) set descText to do shell script "mdls -raw -name kMDItemDescription " & quoted form of filePath if descText is "(null)" then set descText to "【无描述内容】" end if set resultText to resultText & fileName & ":" & linefeed & descText & linefeed & linefeed end repeat display dialog "提取结果:" & linefeed & resultText buttons {"复制到剪贴板", "取消"} default button 1 if button returned of result is "复制到剪贴板" then set the clipboard to resultText end if return input end run
- 保存为「提取MP4描述」,之后在访达里右键选中的MP4文件,就能在「快速操作」里找到这个选项。
特殊情况处理
如果mdls提取不到内容,大概率是系统未索引该文件,或者元数据存在于mdls无法识别的MP4私有字段中。这时可以用ffmpeg(需先通过Homebrew安装)读取:
ffmpeg -i /path/to/your/file.mp4 -show_entries format_tags=description -v quiet -of csv=p=0
把AppleScript里的mdls命令替换成上面的ffmpeg命令即可。
内容的提问来源于stack exchange,提问作者pepe
相关产品推荐
相关产品推荐

