[파이썬] moviepy 다국어 자막 추가하기

Moviepy is a powerful Python library for video editing and processing tasks. One of its useful features is the ability to add subtitles or captions to videos. In this tutorial, we will explore how to add multilingual subtitles to a video using Moviepy in Python.

Prerequisites

Before getting started, make sure you have the following installed:

Adding Multilingual Subtitles

To add multilingual subtitles to a video, we need to follow these steps:

  1. Import the necessary libraries:
    from moviepy.editor import VideoFileClip
    from moviepy.video.tools.subtitles import SubtitlesClip
    
  2. Define the subtitle texts for each language:
    subtitles = {
     'en': [
         {'start': 1, 'end': 3, 'text': 'Hello, how are you?'},
         {'start': 4, 'end': 7, 'text': 'I am doing great.'},
         # Add more subtitles for English
     ],
     'fr': [
         {'start': 1, 'end': 3, 'text': 'Bonjour, comment ça va?'},
         {'start': 4, 'end': 7, 'text': 'Je vais très bien.'},
         # Add more subtitles for French
     ],
     # Add more languages and subtitles if needed
    }
    
  3. Load the video file using VideoFileClip:
    video = VideoFileClip("input.mp4")
    
  4. Create a function to generate subtitle clips for a given language:
    def generate_subtitle_clip(subtitle):
     return SubtitlesClip(subtitle['text'], bg_color='transparent').set_position(('center', 'bottom')).\
         set_start(subtitle['start']).set_end(subtitle['end'])
    
  5. Iterate over each language and generate subtitle clips:
    subtitles_clips = {}
    for lang, subtitles_list in subtitles.items():
     subtitle_clips = []
     for subtitle in subtitles_list:
         subtitle_clip = generate_subtitle_clip(subtitle)
         subtitle_clips.append(subtitle_clip)
     subtitles_clips[lang] = subtitle_clips
    
  6. Composite the video and subtitle clips for each language:
    for lang, subtitle_clips in subtitles_clips.items():
     video_with_subtitle = video.set_duration(subtitle_clips[-1].end).\
         composite(subtitle_clips)
     video_with_subtitle.write_videofile(f"output_{lang}.mp4")
    

That’s it! Now, when you run the script, it will generate separate videos for each language with the corresponding subtitles.

Conclusion

Adding multilingual subtitles to a video using Moviepy in Python is a straightforward process. With the help of the SubtitlesClip class, we can easily create subtitle clips and composite them with the video. This allows us to create videos with subtitles in different languages, enhancing the accessibility and reach of our videos.