gpt4 book ai didi

python - 使用moviepy为电影添加字幕

转载 作者:行者123 更新时间:2023-12-03 16:28:31 26 4
gpt4 key购买 nike

我尝试遵循this example如何向电影剪辑添加字幕:

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

它不是完美的,仍有改进的空间,例如支持不带字幕的时间范围,但这解决了我的问题。

最佳答案

这也适用于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")

关于python - 使用moviepy为电影添加字幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36667702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com