moviepy项目
Github地址
https://github.com/Zulko/moviepy
文档地址
http://zulko.github.io/moviepy/
安装方式
中文教程
音视频合并
1 2 3 4
| import moviepy.editor as mp
video_clip = mp.VideoFileClip(video_file) audio_clip = mp.AudioFileClip(audio_file)
|
1
| final_clip = video_clip.set_audio(audio_clip)
|
- 将合并后的文件写入硬盘,
threads
参数用于控制线程数
1
| final_clip.write_videofile(final_file, threads=4)
|
1 2 3
| video_clip.close() audio_clip.close() final_clip.close()
|
封装成类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import moviepy.editor as mp import os from multiprocessing import cpu_count
class Concat(object): def __init__(self, video, audio, threads: int = -1): _, self.video_name = os.path.split(video) self.video_clip = mp.VideoFileClip(video) self.audio_clip = mp.AudioFileClip(audio) self.final_clip = self.video_clip.set_audio(self.audio_clip) if threads == -1: self.threads = cpu_count() else: self.threads = threads
def save(self, path="./"): video_file = os.path.join(path, self.video_name) self.final_clip.write_videofile(video_file, threads=self.threads)
def close(self): self.video_clip.close() self.audio_clip.close() self.final_clip.close()
def __enter__(self): return self
def __exit__(self, exc_type, exc_val, exc_tb): self.close()
if __name__ == '__main__': with Concat(video="./video_1.mp4", audio="./audio_1.mp4") as c: c.save("./save/1.mp4")
|