参考

https://video.stackexchange.com/questions/16564/how-to-trim-out-black-frames-with-ffmpeg-on-windows

需求描述

有时候需要检测视频开头是否存在纯黑色的帧,从而可以截取掉。

需求实现

ffprobe命令

  1. 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脚本:

  1. def detect_black(media_file: str):
  2. """
  3. 探测视频前2秒钟第一段黑屏的开始和结束时间,便于截掉
  4. :param media_file:
  5. :return:
  6. """
  7. media_path, filename = os.path.split(media_file)
  8. 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'
  9. args = shlex.split(cmd)
  10. result = subprocess.run(args, cwd=media_path, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
  11. content = result.stdout.decode('utf-8')
  12. start = None
  13. stop = None
  14. if content and content.strip():
  15. for line in content.split('\n'):
  16. line: str = line.strip()
  17. if 'start' in line:
  18. start = line.split('=')[1]
  19. elif 'end' in line:
  20. stop = line.split('=')[1]
  21. print(f'content: {content}, start:{start}, stop:{stop}')
  22. return (start,stop)

-read_intervals %+2 用于控制截取的时长是前2秒