阅读量:0
''' ffmpeg version 6.1.1 要求: 合并的视频同分辨率、同帧率 命令: python 多文件夹多视频合并.py --input_videos D:\videos --output_videos D:\out_videos --output_txts D:\out_txt 要求视频文件夹输入目录: --videos --test1 001.mp4 002.mp4 --test2 001.mp4 002.mp4 输出目录(自动创建文件夹): --output_videos test1_sum.mp4 test2_sum.mp4 --output_txts test1.txt test2.txt ''' import argparse import subprocess import os # 创建ffmpeg输入txt def create_input_txt(path_in, path_out_txt): for dir in os.listdir(path_in): try: with open(os.path.join(path_out_txt , '{}.txt'.format(dir)), 'w', encoding='utf-8') as f: path_dir = os.path.join(path_in, dir) for file_name in os.listdir(path_dir): if file_name.split('.')[-1] in ['mp4', 'avi']: f.write(f"file '{os.path.join(path_dir, file_name)}'\n") print(f"视频文件夹 {dir} 创建合并txt成功!") except Exception as e: print(f"视频文件夹 {dir} 创建合并txt失败!") print(e) def run(sum_txt_path, out_video_path): # 创建一个新的进程 p = subprocess.Popen(["ffmpeg", "-f", "concat", "-safe", "0", "-i", f"{sum_txt_path}", "-c", "copy", f"{out_video_path}"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) # 实时打印输出 # for line in p.stdout: # print(line, end='') # end='' 防止打印额外的换行符 # 等待进程结束 p.wait() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input_videos', type=str, default='D:\videos', help='视频输入路径') parser.add_argument('--output_videos', type=str, default='D:\out_videos', help='视频保存路径,自动创建') parser.add_argument('--output_txts', type=str, default='D:\out_txt', help='ffmpeg视频txt保存路径,自动创建') args = parser.parse_args() if not os.path.exists(args.output_videos): os.mkdir(args.output_videos) if not os.path.exists(args.output_txts): os.mkdir(args.output_txts) create_input_txt(args.input_videos, args.output_txts) for txt_name in os.listdir(args.output_txts): try: if os.path.exists(os.path.join(args.output_videos, txt_name.split('.')[0] + '_sum.mp4')): print(f"{txt_name.split('.')[0] + '_sum.mp4'}已存在!, 跳过!") continue run(os.path.join(args.output_txts, txt_name), os.path.join(args.output_videos, txt_name.split('.')[0] + '_sum.mp4')) print(f"{txt_name.split('.')[0] + '_sum.mp4'} 生成成功!") except Exception as e: print(f"{txt_name.split('.')[0] + '_sum.mp4'} 生成失败!") print(e)