Moviepy
The moviepy
module is used to edit video and audio. If we also want to play them, we have to install the pygame
module (as shown here).
Video
Playing a video
A video played using preview()
displays in full-screen mode and can't be stopped.
from moviepy.editor import *
clip = VideoFileClip("video.mp4") # the video object
clip.preview() # this method comes from the pygame module
Rotating a video
from moviepy.editor import *
clip = VideoFileClip("video.mp4")
flipped = clip.rotate(35) # rotating the video by 35 degrees
flipped.write_videofile("video-flipped.mp4") # exporting the video
Trimming a video
from moviepy.editor import *
clip = VideoFileClip("video.mp4")
duration = clip.duration
shortened = clip.subclip(0, duration / 2) # trimming the video by half
shortened.write_videofile("video-shortened.mp4")
Speeding up a video
from moviepy.editor import *
clip = VideoFileClip("video.mp4").fx(vfx.speedx, 2) # speeding up the video two times
clip.write_videofile("video-accelerated.mp4")
Merging video files
from moviepy.editor import *
clip1 = VideoFileClip("video.mp4")
clip2 = VideoFileClip("video2.mp4")
mix = concatenate_videoclips([clip1, clip2]) # merging two video files
mix.write_videofile("mix.mp4")
Creating a video collage
The example below will create four copies of a video, transform each of them differently, and join them into a collage.
from moviepy.editor import *
clip1 = VideoFileClip("video.mp4").margin(10)
clip2 = clip1.fx(vfx.mirror_x)
clip3 = clip1.fx(vfx.mirror_y)
clip4 = clip1.resize(0.60)
clip = clips_array([[clip1, clip2], [clip3, clip4]])
clip.resize(width=480).write_videofile("video-collage.mp4")
.mp4
to .gif
from moviepy.editor import *
clip = VideoFileClip("video.mp4")
clip.write_gif ("video-gif.gif")
Audio
An audio played using preview()
can't be stopped.
from moviepy.editor import *
clip = AudioFileClip("audio.mp3") # the audio object
clip.preview()
Changing the soundtrack in a video
from moviepy.editor import *
videoclip = VideoFileClip("video.mp4")
audioclip = AudioFileClip("audio.mp3")
videoclip2 = videoclip.set_audio(audioclip) # changing the soundtrack
videoclip2.write_videofile("video2.mp4") # exporting the video
Speeding up an audio
from moviepy.editor import *
clip = AudioFileClip("audio.mp3").fx(vfx.speedx, 2) # speeding up the audio two times
clip.write_audiofile("audio-accelerated.mp3") # exporting the audio
Merging audio files
The example below will merge three audio files into one (one soundtrack after another).
from moviepy.editor import *
clip1 = AudioFileClip("audio1.mp3")
clip2 = AudioFileClip("audio2.mp3")
clip3 = AudioFileClip("audio3.mp3")
mix = concatenate_audioclips([clip1, clip2, clip3])
mix.write_audiofile("mix.mp3")