This content originally appeared on DEV Community and was authored by Kevin Naidoo
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:
- Install a PIP library: βpip install moviepyβ
- Some background music, for this demo I am using: A soothing Piano soundtrack by Nicholas Panek
- An animated GIF I whipped up in Canva.
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)
This content originally appeared on DEV Community and was authored by Kevin Naidoo