如何通过AppleScript获取视频的时长、分辨率与帧率信息?
用AppleScript获取视频的时长、分辨率与帧率信息
你说得对,System Events的info for确实搞不定视频的编码参数——它只能读取文件的通用属性,比如大小、创建时间这类,根本碰不到时长、分辨率这些媒体层面的信息。不过不用FFmpeg也有纯AppleScript的解决方案,我给你两个靠谱的路子:
方法一:借助QuickTime Player的AppleScript接口
QuickTime Player自带完整的AppleScript支持,我们可以让它后台打开视频文件,读取完参数再悄悄关掉,完全不打扰你。
set videoPath to "/path/to/your/video.mp4" -- 替换成你的视频文件路径 tell application "QuickTime Player" -- 打开视频文件,设置为后台不可见 set videoDoc to open POSIX file videoPath set visible of videoDoc to false -- 提取所需参数 set videoDuration to duration of videoDoc -- 单位:秒 set videoWidth to width of videoDoc set videoHeight to height of videoDoc set videoFrameRate to frame rate of videoDoc -- 单位:FPS -- 关闭文档,清理资源 close videoDoc end tell -- 弹出结果窗口(也可以改成写入文件或其他处理方式) display dialog "视频信息: 时长: " & videoDuration & " 秒 分辨率: " & videoWidth & "×" & videoHeight & " 帧率: " & videoFrameRate & " FPS"
注意事项:
- 如果视频在Documents、Downloads这类受系统隐私保护的文件夹里,需要给QuickTime Player授权:打开「系统偏好设置」→「安全性与隐私」→「隐私」→「文件与文件夹」,勾选QuickTime Player对应的权限。
- 少数特殊编码的视频可能不被QuickTime Player识别,这种情况下可以试试下面的方法。
方法二:用AppleScriptObjC调用系统底层的AVFoundation框架
这个方法直接调用苹果系统内置的媒体处理框架AVFoundation,不需要打开任何应用,运行更高效、兼容性也更好,支持几乎所有主流视频格式。
use framework "AVFoundation" use scripting additions set videoPath to "/path/to/your/video.mp4" -- 替换成你的视频文件路径 -- 把文件路径转换成AVFoundation能识别的URL对象 set videoURL to current application's NSURL's fileURLWithPath:videoPath -- 创建媒体资源对象 set videoAsset to current application's AVURLAsset's assetWithURL:videoURL -- 异步加载所需的媒体属性 videoAsset's loadValuesAsynchronouslyForKeys:{"duration", "tracks"} completionHandler:(missing value) -- 等待加载完成 repeat while videoAsset's statusOfValueForKey:"duration" error:(reference) is current application's AVKeyValueStatusLoading delay 0.1 end repeat -- 提取时长(转换为秒,AVFoundation返回的是时间刻度值,需要做除法) set durationSeconds to (videoAsset's duration()'s value()) / (videoAsset's duration()'s timescale()) -- 提取视频轨道信息 set videoTracks to videoAsset's tracksWithMediaType:(current application's AVMediaTypeVideo) if videoTracks's |count|() > 0 then set videoTrack to videoTracks's firstObject() -- 提取分辨率 set videoSize to videoTrack's naturalSize() set videoWidth to videoSize's width() set videoHeight to videoSize's height() -- 提取帧率 set frameRate to videoTrack's nominalFrameRate() else error "该文件中未找到视频轨道" end if -- 输出结果 display dialog "视频信息: 时长: " & durationSeconds & " 秒 分辨率: " & videoWidth & "×" & videoHeight & " 帧率: " & frameRate & " FPS"
优势:
- 全程后台运行,不会打开任何窗口,性能更优
- 基于系统底层框架,支持的视频格式比QuickTime Player更全面
- 不需要额外给应用授权(只要脚本本身有文件访问权限就行)
内容的提问来源于stack exchange,提问作者gurkensaas
相关产品推荐
相关产品推荐

