How to Edit Video with MoviePy?

In this article, you will learn how to:
1.Install MoviePy
2.convert MP4 to MP3
3.Merge videos
4.Add music to video
5.Create Gif from video

Official Documentation:

Let’s begin:

Install it via pip

pip install moviepy

Convert MP4 to MP3

from moviepy.editor import *

video = VideoFileClip('yourVideo.mp4')
video.audio.write_audiofile('yourMusic.mp3')

Read video, merge and export

from moviepy.editor import *#Read video and select from 10s~20s
clip1 = VideoFileClip(“1.flv”).subclip(10,20)
#Scale the video size to 60%
clip2 = VideoFileClip(“2.webm”).resize(0.60)
#Merge the video(clip1&clip2)
final_clip = concatenate_videoclips([clip1,clip2])
#Output the video file
final_clip.write_videofile(“Done.mp4”)

Add music to video

from moviepy.editor import VideoFileClip#select video
clip1 = VideoFileClip("targetVideo.mp4")
#extract the audio from clip1
audioclip1 = clip1.audio
#select the video we want to add music to
clip2 = VideoFileClip("targetVideo2.avi")
#add music to clip2
new_video = clip2.set_audio(audioclip1)
#output mp3 and mp4
audioclip1.write_audiofile("outputMUSIC.mp3")
new_video.write_videofile("outputVideo.mp4")

Create GIF

import moviepy.editor as mpy

clip = mpy.VideoFileClip("spcial_video_tzuyu.mp4")
myClip = clip.subclip(10,20) #select from 10s to 20s
#There are 4 different arguments for resize():
#myClip.resize( (1280,720) ) #New resolution: (1280,720)
#myClip.resize(0.5) #width and heigth multiplied by 0.5
#myClip.resize(width=800) #height computed automatically.
#myClip.resize(lambda t : 1+0.02*t) #slow swelling of the clip
#output to GIF
subclip.write_gif("test.gif")

Conclusion

This tutorial teach you how to:

Install MoviePy
Convert MP4 to MP3
Merge videos
Add music to video
Create Gif from video

For more application, please check the official docs

Written by

Machine Learning / Deep Learning / Python / Flutter cakeresume.com/yanwei-liu

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store