1.模块安装
首先,先把需要的模块安装到环境里
pip install moviepy
若安装时报错,可选择运行以下命令,再进行安装。
pip install ez_setep
拓展:
如果需要利用该模块来增加文字,可以考虑安装ImageMagick,安装完该模块后,就可以应用了,但是在Windows环境下,应在moviepy/config_defaults.py文件中指定ImageMagick binary的路径,并叫做convert。
2.关键函数
利用该模块将视频进行合并,主要会用到3个函数:一个是将视频读入的函数;一个是将多个视频合并为一个视频的函数;
一个是将文件写出的函数。
#读入视频
video1=VideoFileClip("adverse.mp4")
#将视频合并为一个视频
#video1为moviepy.video.io.VideoFileClip.VideoFileClip类型
total_clip=concatenate_videoclips([video1,video2,video3])
#将视频写出为mp4
total_clip.write_videofile("out.mp4",fps=24)
3.完整功能代码
现在将完整的合并代码附在下面
from moviepy.editor import *
import os
from natsort import natsorted
# 定义一个筛选文件的函数
def filter_matching_files(path, start=None, end=None):
'''path-文件夹路径;start—以某种字符开头的字符串;end—以某种字符结尾的字符串'''
files_list = []
for root, dirs, files in os.walk(path):
for file in files:
file_abs_path = os.path.join(root, file)
if start is None:
if end:
if file.endswith(end):
files_list.append(file_abs_path)
elif start:
if end is None:
if file.startswith(start):
files_list.append(file_abs_path)
elif end:
if file.startswith(start) & file.endswith(end):
files_list.append(file_abs_path)
else:
continue
return files_list
#定义合并的视频
def concat_video(in_path, out_path, file_name=None, start=None, end=None):
'''in_path—输入的文件夹路径;out_path—输出的文件夹路径;file_name—合并后的文件名称(需要加后缀);start—以某种字符开头的字符串;end—以某种字符结尾的字符串'''
video_list = []
files_list = filter_matching_files(in_path, start, end)
# 对文件进行排序
files_list = natsorted(files_list)
for file in files_list:
video = VideoFileClip(file)
video_list.append(video)
video_result = concatenate_videoclips(video_list)
# 输出的完整路径
if file_name is None:
file_name = "video.mp4"
file_abs_path = os.path.join(out_path, file_name)
video_result.write_videofile(file_abs_path, fps=24, remove_temp=False)
#进行调用
in_path=r"E:\\"
out_path=r"E:\test"
out_name="test.mp4"
#对以adverse开头的mp4文件进行合并
concat_video(in_path,out_path,out_name,'adverse','.mp4')