How to Add Text to Video using Python?

The majority of social media platforms automatically play videos without sound. By including text in videos, you can capture the attention of viewers as they scroll through their feeds. To add text to a video using Python, you'll need a video editing API. The following Python code example shows how to do it with only a few lines:

Input Code
import requests

json = {
 'source': {
  'output_format': 'mp4',
  'elements': [
   {
    'type': 'video',
    'track': 1,
    'source': 'https://cdn.creatomate.com/demo/mountains.mp4'
   },
   {
    'type': 'text',
    'track': 2,
    'y': '63.12%',
    'width': '90.48%',
    'height': '15.12%',
    'x_alignment': '50%',
    'y_alignment': '50%',
    'text': 'Add your custom text here. ✍️',
    'font_family': 'Roboto',
    'font_weight': '500',
    'font_size_maximum': '10 vmin',
    'background_color': '#ffffff',
    'background_x_padding': '52%',
    'background_border_radius': '26%'
   }
  ]
 }
}

response = requests.post(
 'https://api.creatomate.com/v1/renders',
 headers={
  # Find your API key under 'Project Settings' in your account:
  # https://creatomate.com/docs/api/rest-api/authentication
  'Authorization': 'Bearer Your-API-Key',
  'Content-Type': 'application/json',
 },
 json=json
)

# Wait a minute, then visit the URL provided in the response:
print(response.json())

Output Video

How it works: As it uses a straightforward REST API, the API requires only the "requests" package from the Python standard library. There are two elements included in this composition: a video placed on track one, followed by a text placed on track two. Placing these elements on separate tracks ensures that they are displayed simultaneously.

To ensure the text adapts to the background video's dimensions, make sure to use relative units (%) for the position attributes. This approach allows the text to automatically adjust based on the video's size. For specific stylistic preferences, you can use the font properties. If you want to achieve the Instagram aesthetic, give the text a rounded background. On the other hand, if you prefer the TikTok style, you can use the stroke properties to achieve that effect. Additionally, the text element supports emojis, so feel free to include them into your text.

To explore various styles and animations, you can use the online code video editor. This tool enables you to create personalized video scenes, which can later be imported into Python for further implementation.

Edit this Code Example in the Video Editor

Easily design your own video templates using the online editor. Then, export your templates as JSON and integrate them into your Python application to create any kind of video – completely through code.

Related Python Video Editing Questions

Start automating today

Start with a full-featured trial with 50 credits, no credit card required.
Get started for free