使用Python 编写的 ffmepg 处理视频的脚本

拼接视频片段

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. """
  4. 使用 ffmpeg 截取视频片段并且重新拼接
  5. 使用方式:
  6. 提供文件格式如下:比如 input.txt
  7. ./input.mp4
  8. 00:01:00 00:02:00
  9. 00:04:00 00:08:00
  10. """
  11. import os
  12. import sys
  13. CONCAT_FILE = '_concat.txt'
  14. def read_input(filepath):
  15. with open(filepath) as f:
  16. lines = f.readlines()
  17. input_mp4 = lines[0].strip()
  18. suffix = input_mp4.split('.')[-1]
  19. for idx, start_end_time in enumerate(lines[1:]):
  20. pair = start_end_time.split()
  21. start, end = pair[0], pair[1]
  22. part_name = 'part_' + str(idx) + '.' + suffix
  23. cmd = "ffmpeg -i {} -ss {} -to {} -c copy {}".format(
  24. input_mp4, start, end, part_name
  25. )
  26. print(cmd)
  27. os.system(cmd)
  28. yield part_name
  29. def write_part_to_file(part_list):
  30. dir_path = os.path.dirname(os.path.realpath(__file__))
  31. filepath_list = []
  32. for part_name in part_list:
  33. print(part_name)
  34. path = os.path.join(dir_path, part_name)
  35. filepath_list.append(path)
  36. with open(CONCAT_FILE, 'w') as f:
  37. for path in filepath_list:
  38. f.write("file '{}'\n".format(path))
  39. return filepath_list
  40. def concat_video():
  41. cmd = "ffmpeg -f concat -safe 0 -i {} -c copy output.mp4".format(CONCAT_FILE)
  42. os.system(cmd)
  43. def remove(filepath_list):
  44. """移除中间文件"""
  45. for path in filepath_list + [CONCAT_FILE]:
  46. if os.path.exists(path):
  47. os.remove(path)
  48. def main():
  49. try:
  50. inputfile = sys.argv[1]
  51. except KeyError:
  52. print('must need input.txt')
  53. partnames = list(read_input(inputfile))
  54. filepath_list = write_part_to_file(partnames)
  55. concat_video()
  56. remove(filepath_list)
  57. if __name__ == '__main__':
  58. main()

递归统计一个文件夹下的所有视频时长

  1. # -*- coding: utf-8 -*-
  2. """
  3. 递归统计一个目录下所有视频文件的总时长。比如笔者用来统计课程的内容总时长。
  4. pip install moviepy
  5. 如果安装报错,尝试升级
  6. pip install --upgrade setuptools
  7. 使用方法:
  8. python compute_duration.py --path ~/Movies/ --type .mp4
  9. 参考:https://blog.csdn.net/qq_22210253/article/details/86684658
  10. """
  11. import os
  12. import datetime
  13. import argparse
  14. from moviepy.editor import VideoFileClip
  15. def main():
  16. parser = argparse.ArgumentParser(
  17. description='Compute Total Time of a Series of Videos')
  18. parser.add_argument("--path", metavar="PATH", default=".",
  19. help="the root path of the videos(default: .)")
  20. parser.add_argument("--type", metavar="TYPE", default=".mkv",
  21. help="the type of the videos(default: .mkv)")
  22. args = parser.parse_args()
  23. filelist = []
  24. for a, b, c in os.walk(args.path):
  25. for name in c:
  26. fname = os.path.join(a, name)
  27. if fname.endswith(args.type):
  28. filelist.append(fname)
  29. ftime = 0.0
  30. for file in sorted(filelist):
  31. clip = VideoFileClip(file)
  32. print("{}: {}秒".format(file, clip.duration))
  33. ftime += clip.duration
  34. print("%d seconds: " % ftime, str(datetime.timedelta(seconds=ftime)))
  35. if __name__ == "__main__":
  36. main()