Merge two videos using moviepy in Python
In this tutorial, we are going to see how to merge or join two videos using moviepy in Python. moviepy is a Python library used for video editing and processing. It can read and write all audio and video formats including MP4, GIF, etc.
First, install the moviepy library.
pip install moviepy
Also, install the ffmpeg library, which is a Python wrapper for FFmpeg.
pip install ffmpeg
Now, import the useful functions from the moviepy library.
from moviepy.editor import VideoFileClip, concatenate_videoclips
VideoFileClip
is a function that is used to access the video file.
concatenate_videoclips
is a function that is used to join or concatenate two video files.
Now read the sample video files using the VideoFileClip
function. It takes the file path as an argument.
clip1 = VideoFileClip("F:\sample_1.mp4") #5 seconds video clip2 = VideoFileClip("F:\sample_2.mp4") #10 seconds video
Now join the two video clips using the concatenate_videoclips
function. It takes an array of video clips as an argument.
final_clip = concatenate_videoclips([clip1,clip2])
Save the above-concatenated video as a new video file. This is done by using the write_videofile function. It is used to write video files.
final_clip.write_videofile("new.mp4") #16 seconds video
Output:
Moviepy - Building video new.mp4. MoviePy - Writing audio in newTEMP_MPY_wvf_snd.mp3 MoviePy - Done. Moviepy - Writing video new.mp4 Moviepy - Done ! Moviepy - video ready new.mp4
Finally, display the merged video to testify.
final_clip.ipython_display(width=480)
ipython is a toolkit that has display attributes used to open and view images, and videos in python code.
Output:
Moviepy - Building video __temp__.mp4. MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3 MoviePy - Done. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4
Also see, Create a video with images in Python
Leave a Reply