我试图按照这个示例如何为影片剪辑添加字幕:
from moviepy.video.tools.subtitles import SubtitlesClip
from moviepy.video.io.VideoFileClip import VideoFileClip
subs = [((0, 3), 'sub1'),
((3, 7), 'sub2'),
((9, 11), 'sub3'),
((11, 16), 'sub4')]
subtitles = SubtitlesClip(subs)
clip = VideoFileClip(video_fname)
video = movedit.CompositeVideoClip([clip, subtitles])
video.to_videofile(output_video_name)
但是输出的电影没有字幕。难道我做错了什么?顺便说一句,subtitles.py不适用于 python 3,这行代码
subtitles = [(map(cvsecs, tt),txt) for tt, txt in subtitles]
需要改为
subtitles = [(list(map(cvsecs, tt),txt)) for tt, txt in subtitles]
编辑
最终,我以艰难的方式创建了字幕:
from moviepy import editor
import os.path as op
def annotate(clip, txt, txt_color='red', fontsize=50, font='Xolonium-Bold'):
""" Writes a text at the bottom of the clip. """
txtclip = editor.TextClip(txt, fontsize=fontsize, font=font, color=txt_color)
cvc = editor.CompositeVideoClip([clip, txtclip.set_pos(('center', 'bottom'))])
return cvc.set_duration(clip.duration)
video = editor.VideoFileClip(op.join(movie_fol, movie_name))
subs = [((0, 4), 'subs1'),
((4, 9), 'subs2'),
((9, 12), 'subs3'),
((12, 16), 'subs4')]
annotated_clips = [annotate(video.subclip(from_t, to_t), txt) for (from_t, to_t), txt in subs]
final_clip = editor.concatenate_videoclips(annotated_clips)
final_clip.write_videofile(op.join(movie_fol, out_movie_name))
它并不完美,还有改进的空间,比如支持没有字幕的时间范围,但它解决了我的问题。