#视频合并代码
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 可执行文件路径
ffmpeg_path = r'C:\Users\17777\Downloads\视频合并\ffmpeg-master-latest-win64-gpl-shared\bin\ffmpeg.exe' # 替换为你的 FFmpeg 路径
# 获取视频文件夹中的所有视频文件
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 命令
ffmpeg_cmd = [
ffmpeg_path, # FFmpeg 可执行文件路径
'-y', # 覆盖输出文件
'-f', 'concat', # 使用 concat 格式
'-safe', '0', # 允许使用不安全的文件路径
'-i', 'filelist.txt', # 输入文件列表
'-c', 'copy', # 直接复制编解码数据
output_file # 输出的合并视频文件路径
]
# 打印 FFmpeg 命令(可选)
print(' '.join(ffmpeg_cmd))
# 执行 FFmpeg 命令
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)