DEV Community

Kevin Naidoo
Kevin Naidoo

Posted on

Simple TikTok 🎬 video using Python

Whether I'm building a little script, a web app, or doing machine learning, Python is always a handy little language to have in my toolbox.

As is the "Pythonic" way, there's a package for everything and anything in Python, and video is no different.

In this quick guide, I'll show you how to make a simple TikTok short video with just a few lines of code.

Getting started

To get started we'll need 3 things:

Building our "movie maker" script

First, we need to load our ".gif" file:

from moviepy.editor import VideoFileClip, AudioFileClip
video_clip = VideoFileClip("./background.gif")

Next, let's load our audio file:

bg_music = AudioFileClip("./piano.mp3")

Finally, we add our sound to the GIF:

video_clip = video_clip.set_audio(bg_music)
video_clip.write_videofile("./video.mp4", codec='libx264', fps=24)
video_clip.close()
bg_music.close()

And Voila! You should now have a video file ("video.mp4") in the current directory with our final TikTok short.

Here's the full script:

from moviepy.editor import VideoFileClip, AudioFileClip

video_clip = VideoFileClip("./background.gif")
bg_music = AudioFileClip("./piano.mp3")
video_clip = video_clip.set_audio(bg_music)
video_clip.write_videofile("./video.mp4", codec='libx264', fps=24)

video_clip.close()
bg_music.close()

You can learn more about "moviepy" here: https://pypi.org/project/moviepy/

Tip: To shorten the audio so that it fits the video length:

bg_music = AudioFileClip("./piano.mp3") \
    .audio_loop(duration=video_clip.duration)

Top comments (1)

 
sreno77 profile image
Scott Reno •

Concise and easy to follow... awesome post!