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

拼接视频片段

#!/usr/bin/env python# -*- coding:utf-8 -*-"""使用 ffmpeg 截取视频片段并且重新拼接使用方式:提供文件格式如下:比如 input.txt./input.mp400:01:00 00:02:0000:04:00 00:08:00"""importosimportsysCONCAT_FILE='_concat.txt'defread_input(filepath):withopen(filepath)asf:lines=f.readlines()input_mp4=lines[0].strip()suffix=input_mp4.split('.')[-1]foridx,start_end_timeinenumerate(lines[1:]):pair=start_end_time.split()start,end=pair[0],pair[1]part_name='part_'+str(idx)+'.'+suffixcmd="ffmpeg -i{} -ss{} -to{} -c copy{}".format(input_mp4,start,end,part_name)print(cmd)os.system(cmd)yieldpart_namedefwrite_part_to_file(part_list):dir_path=os.path.dirname(os.path.realpath(__file__))filepath_list=[]forpart_nameinpart_list:print(part_name)path=os.path.join(dir_path,part_name)filepath_list.append(path)withopen(CONCAT_FILE,'w')asf:forpathinfilepath_list:f.write("file '{}'\n".format(path))returnfilepath_listdefconcat_video():cmd="ffmpeg -f concat -safe 0 -i{} -c copy output.mp4".format(CONCAT_FILE)os.system(cmd)defremove(filepath_list):"""移除中间文件"""forpathinfilepath_list+[CONCAT_FILE]:ifos.path.exists(path):os.remove(path)defmain():try:inputfile=sys.argv[1]exceptKeyError:print('must need input.txt')partnames=list(read_input(inputfile))filepath_list=write_part_to_file(partnames)concat_video()remove(filepath_list)if__name__=='__main__':main()

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

# -*- coding: utf-8 -*-"""递归统计一个目录下所有视频文件的总时长。比如笔者用来统计课程的内容总时长。pip install moviepy如果安装报错,尝试升级pip install --upgrade setuptools使用方法:python compute_duration.py --path ~/Movies/ --type .mp4参考:https://blog.csdn.net/qq_22210253/article/details/86684658"""importosimportdatetimeimportargparsefrommoviepy.editorimportVideoFileClipdefmain():parser=argparse.ArgumentParser(description='Compute Total Time of a Series of Videos')parser.add_argument("--path",metavar="PATH",default=".",help="the root path of the videos(default: .)")parser.add_argument("--type",metavar="TYPE",default=".mkv",help="the type of the videos(default: .mkv)")args=parser.parse_args()filelist=[]fora,b,cinos.walk(args.path):fornameinc:fname=os.path.join(a,name)iffname.endswith(args.type):filelist.append(fname)ftime=0.0forfileinsorted(filelist):clip=VideoFileClip(file)print("{}:{}秒".format(file,clip.duration))ftime+=clip.durationprint("%d seconds: "%ftime,str(datetime.timedelta(seconds=ftime)))if__name__=="__main__":main()