Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

One, foreword

Anyone who has swiped Tiktok or any other video platform will notice. Almost every video will have a platform-specific AD opening, which is not manually added by the video author, but automatically generated by the video platform. So how do you generate a beginning like this? Today we’ll take a look.

2. Moviepy module

Moviepy was mentioned earlier when we converted videos to GIFs. Today we are going to use moviepy. Moviepy is python’s professional module for handling video, including video clips, audio additions and deletions, subtitle additions and deletions, and more. It’s very functional.

1, install,

To install Moviepy, it is very simple:

pip install moviepy
Copy the code

There are many submodules in Moviepy, of which Editor is one of the more commonly used, importing the following:

from moviepy.editor import VideoFileClip
Copy the code

Now we can use it. It should be noted that Moviepy needs to be combined with ffMPEG to be fully functional. This article doesn’t use much functionality, so I won’t go into the details of ffMPEG configuration.

2. Easy to use

Let’s start with some simple operations:

from moviepy.editor import VideoFileClip
# Read the video file
clip = VideoFileClip("test.mp4")
# Video clip
video = clip.subclip(1.2)
# Save the clip
video.write_videofile("1.mp4")
Copy the code

Above we will focus on the use of subclip, which can realize the video clip, we can pass in the start time and end time. The above indicates the intercept from the first second to the second second. This can also be edited in the following way:

from moviepy.editor import VideoFileClip
clip = VideoFileClip("test.mp4")
# Video clip
video = clip.subclip((1.20), (2.40))
video.write_videofile("1.mp4")
Copy the code

This is a clip from 1:20 to 2:40. And it’s very intuitive to understand.

Add a beginning to the video

The operation of merging videos is required as follows:

from moviepy.editor import VideoFileClip
from moviepy.video.compositing.concatenate import concatenate_videoclips
# Read video
clip1 = VideoFileClip("1.mp4")
clip2 = VideoFileClip("2.mp4")
# Merge video
video = concatenate_videoclips([clip1, clip2])
# Save video
video.write_videofile("result.mp4")
Copy the code

Above we implemented the video merge primarily through the concatenate_videoclips function, passing in a list of clips.