For some cases we need to append captions to a video.In my case I was working with a problem related to video-description (captioning) This python code helps to add captions to a video.I was wondering if someone need a solution feel free to experiment the code.
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")
This works well for a single caption..You can play with a parameters for changes
"""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)