moviepy为视频添加字幕
import os,pathlib,randomfrom os.path import splitext,isfile
from moviepy.editor import (VideoFileClip,TextClip,CompositeVideoClip)
src_path=os.path.join(os.getcwd(),u"audios")
print(src_path)
src_path=pathlib.Path(src_path)
print(src_path)
mp4_list=[]
txt_list=[]
for item in src_path.iterdir():
if ".mp4" in str(item):
mp4_list.append(str(item))
elif ".txt" in str(item):
txt_list.append(str(item))
print(mp4_list)
print(txt_list)
if len(mp4_list)>0:
src_mp4=random.choice(mp4_list) #随机选取一个音频文件并得到相应的txt文件
src_txt=src_mp4.replace("mp4","txt")
else:
print("No mp4_file exist!")
exit()
src_txt=random.choice(txt_list)
video=VideoFileClip(src_mp4)
w,h=video.w,video.h
txts=[]
tran_to_srt_list=[]
each_of_time_start=0
each_of_time_duration=0
with open(src_txt,'r',encoding='utf-8') as f:
# print(f.readlines())
for line in f.readlines():
each_of_time_duration=(len(line)-1)/(180/60)
txt=(TextClip(line,fontsize=40,font="STLITI.TTF",size=(w-20,h),
align="center",color="black")
.set_position((10,h-150))
.set_duration(each_of_time_duration).set_start(each_of_time_start))
txts.append(txt)
each_of_time_start=each_of_time_start+each_of_time_duration+0.5
print(len(txts))
print(*txts)
video=CompositeVideoClip([video,*txts])
运行后,到最后这一步出错:TypeError: cannot unpack non-iterable NoneType object