10

我试图按照这个示例如何为影片剪辑添加字幕:

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))

它并不完美,还有改进的空间,比如支持没有字幕的时间范围,但它解决了我的问题。

4

1 回答 1

6

这也适用于python3

from moviepy.editor import *
from moviepy.video.tools.subtitles import SubtitlesClip

generator = lambda txt: TextClip(txt, font='Arial', fontsize=24, color='white')
subs = [((0, 4), 'subs1'),
        ((4, 9), 'subs2'),
        ((9, 12), 'subs3'),
        ((12, 16), 'subs4')]

subtitles = SubtitlesClip(subs, generator)

video = VideoFileClip("input.mp4")
result = CompositeVideoClip([video, subtitles.set_pos(('center','bottom'))])

result.write_videofile("output.mp4", fps=video.fps, temp_audiofile="temp-audio.m4a", remove_temp=True, codec="libx264", audio_codec="aac")
于 2021-03-22T18:56:05.723 回答