Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding subtitles to a movie using moviepy

I'm tried to follow this example how to add subtitles to a movie clip:

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)

But the output movie turned out without subtitles. Am I doing something wrong? btw, the subtitles.py doesn't work with python 3, this line of code

subtitles = [(map(cvsecs, tt),txt) for tt, txt in subtitles]

Is needed to be changed to

subtitles = [(list(map(cvsecs, tt),txt)) for tt, txt in subtitles]

Edit

Eventually I've created subtitles the hard way:

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

It's not perfect, there is still room for improvement, like supporting time ranges without subtitles, but it solved my problem.

like image 205
Noam Peled Avatar asked Apr 16 '16 17:04

Noam Peled


1 Answers

This also works with 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")
like image 196
Sandipan Dey Avatar answered Oct 22 '22 00:10

Sandipan Dey