本文正在参加「Python主题月」,详情查看 juejin.cn/post/697953…
看到掘金有主题月活动,忽然间想起来以前为了帮公司运营搞视频合并 写过一个程序 今天翻出来 作为我的参加文章 使用moviepy以及subprocess 来进行音频和视频的操作
from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioClip, AudioFileClip
import os, re, random
from natsort import natsorted
import time
from itertools import product
import subprocess
from pydub import AudioSegment
import random
class Compose():
def __init__(self):
self.audios = 'test.mp3'
self.audiolist = []
self.videopath = ""
self.vdpathlist = []
self.count = 0
self.hechengpath = ""
self.is_make_hunhe=False
def check_num(self, arr): # 过滤mp3
pattern = re.compile('[0-9]+')
for v in arr:
match = pattern.findall(v)
if match and 'mp3' not in v:
return True
else:
return False
def takevideo(self): # 分组mp3
try:
os.remove(self.audios)
except:
self.hechengpath = os.getcwd()
videolist = []
for root, dirs, names in os.walk(self.hechengpath):
if self.check_num(names):
self.vdpathlist.append(root)
names = [root + '\\' + name for name in names]
videolist.append(names)
for name in names:
if "mp3" in name:
fromdir = os.path.join(root, name)
self.audiolist.append(fromdir)
return videolist
def video_add_mp3(self, times, file_name, mp3_file): # 给视频添加声音
outfile_name = file_name.split('.')[0] + '-end.mp4'
cmd = "ffmpeg -i %s -i %s -t 7.1 -y %s"
subprocess.call(cmd % (mp3_file, file_name, times, outfile_name))
# subprocess.call("ffmpeg -i %s -i %s -t %s -y %s" % (mp3_file, file_name, times, outfile_name))
return outfile_name
def takename(self, i): # 拼接视频名字
strs = "".join(list(i))
for j in self.vdpathlist:
strs = strs.replace(j, "").strip('\\').replace(".mov", "").replace(".MOV", "").replace(".mp4", "").replace(".mp3", "")
strs = strs.replace("\\", "+")
return strs
def synthetic_two_audio(self): # 把两个声音混合
if self.is_make_hunhe:
if len(self.audiolist) > 1:
mp3a = self.audiolist[0]
mp3b = self.audiolist[1]
subprocess.call(
"ffmpeg -i %s -i %s -filter_complex amerge -ac 2 -c:a libmp3lame -q:a 4 %s" % (mp3a, mp3b, self.audios))
else:
self.audios = self.audiolist[0]
else:
self.audios=random.choice(self.audiolist)
def hecheng(self): # 合成声音
lists = self.takevideo()
for i in product(*lists):
self.synthetic_two_audio()
videopath = self.takename(i) + ".mp4"
videolist = [VideoFileClip(j, audio=True).resize([1080, 1920]) for j in i]
finalclip = concatenate_videoclips(videolist, method="compose")
times = finalclip.duration
finalclip.write_videofile(filename=videopath, codec='libx264', bitrate=('1000000', '2000000',), threads=5)
self.video_add_mp3(times, videopath, self.audios)
# os.remove(videopath)
if __name__ == "__main__":
cmp = Compose()
cmp.hecheng()
复制代码