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:
- Python (version 3 or above)
- Moviepy (install using
pip install moviepy
)
Adding Multilingual Subtitles
To add multilingual subtitles to a video, we need to follow these steps:
- Import the necessary libraries:
from moviepy.editor import VideoFileClip from moviepy.video.tools.subtitles import SubtitlesClip
- 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 }
- Load the video file using
VideoFileClip
:video = VideoFileClip("input.mp4")
- 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'])
- 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
- 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.