Python中如何编写合并小视频的脚本
深夜思考人生的时候会找些资料来格物致知。不过有的资料总是分成若干个小文件。。
按说现在视频播放器都会自动按顺序播放,但中间总会有点小停顿。无赖只好找视频编辑软件合起来。。
更无赖的是大多编辑软件要么收费、要么有水印。
只好请出 ffmpeg 了, 在用 ffmpeg 前,要先对文件名进行排序。按说 sort 命令就好了,但字母数字混合的不好搞。
Google 了一下,也没找到相关命令,只好按需写段小脚本。
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
def getFileList(path):
fileListTmp = os.listdir(path)
fileList = []
for i in fileListTmp:
if i[-3:] == ‘.ts’:
fileList.append(i)
fileList.sort(key=lambda x: int(os.path.splitext(x)[0].split(‘720p’)[1]))
txt = os.path.join(path,‘b.txt’)
with open(txt,‘w’) as f:
for i in fileList:
f.write('file ’ + str(path) + ‘/’ + i + ‘\n’)
f.close()
return txt
def main():
path = os.path.abspath(sys.argv[-1])
txt = getFileList(path)
outFileName = path.split(’/’)[-1] + ‘.mp4’
output = os.path.join(path,outFileName)
os.system('ffmpeg -f concat -safe 0 -i ’ + txt + ’ -c copy ’ + output)
print(‘Your video file at {}’.format(output))
os.system('rm ’ + txt)
if name == ‘main’:
main()
欢迎留下更好的解决方案。
Python中如何编写合并小视频的脚本
我来写一个合并小视频的Python脚本。用moviepy库最方便:
from moviepy.editor import VideoFileClip, concatenate_videoclips
import os
def merge_videos(video_paths, output_path="merged_video.mp4"):
"""
合并多个视频文件
Args:
video_paths: 视频文件路径列表
output_path: 输出文件路径
"""
clips = []
for path in video_paths:
if os.path.exists(path):
clip = VideoFileClip(path)
clips.append(clip)
print(f"已加载: {path}")
else:
print(f"文件不存在: {path}")
if not clips:
print("没有找到可合并的视频文件")
return
# 合并视频
final_clip = concatenate_videoclips(clips, method="compose")
# 写入输出文件
final_clip.write_videofile(output_path, codec="libx264", audio_codec="aac")
# 关闭所有剪辑以释放资源
for clip in clips:
clip.close()
final_clip.close()
print(f"视频合并完成,保存为: {output_path}")
# 使用示例
if __name__ == "__main__":
# 指定要合并的视频文件路径
video_files = [
"video1.mp4",
"video2.mp4",
"video3.mp4"
]
# 合并视频
merge_videos(video_files, "final_output.mp4")
安装依赖:
pip install moviepy
脚本特点:
- 自动检查文件是否存在
- 支持多种视频格式(MP4、AVI、MOV等)
- 保持原始视频的音频
- 使用compose方法处理不同分辨率的视频
进阶用法: 如果需要处理文件夹中的所有视频:
import glob
def merge_all_videos_in_folder(folder_path, output_path="merged_video.mp4"):
# 获取文件夹中所有视频文件
video_extensions = ['*.mp4', '*.avi', '*.mov', '*.mkv']
video_files = []
for ext in video_extensions:
video_files.extend(glob.glob(os.path.join(folder_path, ext)))
# 按文件名排序
video_files.sort()
if video_files:
merge_videos(video_files, output_path)
else:
print("文件夹中没有找到视频文件")
# 使用示例
merge_all_videos_in_folder("./videos", "merged_result.mp4")
这个脚本能搞定大部分视频合并需求。
总结:用moviepy的concatenate_videoclips函数最省事。
f.close() 是不是多余
这个我一般用 Amazon Elastic Transcoder 处理
ffmpeg -f concat -i “list.txt” -vf “select=concatdec_select” out.mp4
大概这样就行。list.txt 格式参考下文档。可以设置每段视频起止时间。
可以看下这个用 cython 包装 ffmpeg 的项目:
http://docs.mikeboers.com/pyav/develop/
https://github.com/mikeboers/PyAV
moviepy
这个可以吗?
sort -V: natural sort of (version) numbers within text

