视频合并代码
import os
import re
import subprocess
def natural_sort_key(s):
return [int(text) if text.isdigit() else text.lower() for text in re.split('(\d+)', s)]
def merge_videos(video_folder, output_file):
ffmpeg_path = r'C:\Users\17777\Downloads\视频合并\ffmpeg-master-latest-win64-gpl-shared\bin\ffmpeg.exe'
video_files = [f for f in os.listdir(video_folder) if f.endswith('.mp4')]
video_files.sort(key=natural_sort_key)
with open('filelist.txt', 'w', encoding='utf-8') as f:
for video_file in video_files:
f.write(f"file '{os.path.join(video_folder, video_file)}'\n")
ffmpeg_cmd = [
ffmpeg_path,
'-y',
'-f', 'concat',
'-safe', '0',
'-i', 'filelist.txt',
'-c', 'copy',
output_file
]
print(' '.join(ffmpeg_cmd))
try:
subprocess.run(ffmpeg_cmd, check=True, capture_output=True)
print(f'合并完成,输出文件保存为: {output_file}')
except subprocess.CalledProcessError as e:
print(f'合并过程中出错: {e.stderr.decode("utf-8")}')
if __name__ == '__main__':
video_folder = r'C:\Users\17777\Downloads\视频合并\小苹果1'
output_file = r'C:\Users\17777\Downloads\视频合并\小苹果合并1\小苹果合并.mp4'
merge_videos(video_folder, output_file)
演示地址
https://www.bilibili.com/video/BV1HfVjeyEab/