[Python] Adding subtitles to a movie using moviepy

Discussão em 'Python' iniciado por Stack, Abril 24, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página