Sum*_*i J 5 python animation caption closed-captions moviepy
在某些情况下,我们需要向视频添加字幕。就我而言,我正在处理与视频描述(字幕)相关的问题。此 python 代码有助于向视频添加字幕。我想知道是否有人需要解决方案,请随意来试验代码。
import moviepy.editor as mp
my_video = mp.VideoFileClip("video.mp4") #video path
w,h = moviesize = my_video.size
my_text = mp.TextClip("A man and a women are sitting on a bench", font="Amiri-regular", color="white", fontsize=34)
txt_col = my_text.on_color(size=(my_video.w + my_text.w, my_text.h+5), color=(0,0,0), pos=(6,"center"), col_opacity=0.6)
txt_mov = txt_col.set_pos( lambda t: (max(w/30,int(w-0.5*w*t)),max(5*h/6,int(100*t))) )
final = mp.CompositeVideoClip([my_video,txt_mov])
final.subclip(0,17).write_videofile("final.mp4",fps=24,codec="libx264")
Run Code Online (Sandbox Code Playgroud)
这对于单个标题很有效。您可以使用参数进行更改
"""Multiple Text in single video"""
import moviepy.editor as mp
my_video = mp.VideoFileClip("/home/user/cap/video.mp4").subclip(0,10)
print(my_video.duration)
w,h = moviesize = my_video.size
texts = []
with open("/home/user/cap/caption.txt") as file:
for line in file:
line = line.strip() #or some other preprocessing
texts.append(line)
print(type(texts))
starts = [0,2,4,6,8,10,12,14,16,18,20] # or whatever
durations = [2,2,2,2,2] #Time duraton between captions
t = 0
txt_clips = []
for text,t,duration in zip(texts, starts, durations):
txt_clip = mp.TextClip(text,font="Amiri-regular", color="black", fontsize=29)
txt_clip = txt_clip.set_start(t)
txt_col = txt_clip.on_color(size=(my_video.w + txt_clip.w, txt_clip.h+5), color=(0,0,0), pos=(6,"center"), col_opacity=0.6)
txt_clip = txt_clip.set_pos( lambda t: (max(w/30,int(w-0.5*w*t)),max(5*h/6,int(100*t))) ).set_duration(duration)
txt_clips.append(txt_clip)
print(txt_clips)
print(type(txt_clips))
final_video = mp.CompositeVideoClip([my_video, txt_clips[0],txt_clips[1],txt_clips[2],txt_clips[3],txt_clips[4]])
final_video.write_videofile("TEXT.mp4",fps=24)
Run Code Online (Sandbox Code Playgroud)