参考
https://video.stackexchange.com/questions/16564/how-to-trim-out-black-frames-with-ffmpeg-on-windows
需求描述
有时候需要检测视频开头是否存在纯黑色的帧,从而可以截取掉。
需求实现
ffprobe命令
ffprobe -f lavfi -i "movie=dc1a1f56bf611dc90eb4e707ba3e3c10.webm,blackdetect[out0]" -show_entries tags=lavfi.black_start,lavfi.black_end -of default=nw=1 -v quiet
输出结果如下:
TAG:lavfi.black_start=0.32 TAG:lavfi.black_start=0.32 TAG:lavfi.black_end=0.68 TAG:lavfi.black_end=0.68
python脚本
下面是基于上面ffprobe命令构建的python3脚本:
def detect_black(media_file: str):
"""
探测视频前2秒钟第一段黑屏的开始和结束时间,便于截掉
:param media_file:
:return:
"""
media_path, filename = os.path.split(media_file)
cmd = f'ffprobe -f lavfi -i "movie={filename},blackdetect[out0]" -show_entries tags=lavfi.black_start,lavfi.black_end -of default=nw=1 -v quiet -read_intervals %+2'
args = shlex.split(cmd)
result = subprocess.run(args, cwd=media_path, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
content = result.stdout.decode('utf-8')
start = None
stop = None
if content and content.strip():
for line in content.split('\n'):
line: str = line.strip()
if 'start' in line:
start = line.split('=')[1]
elif 'end' in line:
stop = line.split('=')[1]
print(f'content: {content}, start:{start}, stop:{stop}')
return (start,stop)
-read_intervals %+2 用于控制截取的时长是前2秒