python calls ffmpeg command line tools to conveniently operate the video example implementation process

  • 2021-12-12 04:41:05
  • OfStack

The most important thing in catalog is to cut video calculation segmentation to get video length segmentation to get file code integration summary reference

Wen Li Xiaofei

Source: Python Technology "ID: pythonall"

Recently, there is a new task, which needs to split the competition video into short segments within two minutes for publishing on the short video platform.

I thought it was a once-in-a-lifetime job. As a result, the video data of the competition was huge, and the length of the video files was not 1, which could not be handled manually at all, so Python saved me again.

What are you waiting for? Let's get to work!

The most important thing

No matter what you do, you should analyze what is the most important thing, then concentrate on conquering it, and then continue to find the most important thing.

It's not a big project for our task, but we still need to find the most important thing to start, step by step, and finally solve the whole problem.

On the whole, we need to read video files from one directory, then crop each video file, and finally save the processed files.

What is the most important thing in this process? In my opinion, it is video clipping. If you can't clip the video conveniently, the other 1-cut work will be in vain, right?

Crop video

Nowadays, short videos are very popular, and there are many video editing software with rich functions, but all we need is clipping function, which needs to be called programmatically, so the most suitable one is ffmpeg [1].

ffmpeg is a command-line tool, powerful, can be called programmatically.

Download the corresponding operating system version from ffmpeg official website, and I downloaded Windows version [2].

After downloading, unzip it to a directory, and then configure bin in the directory to the environment variable. Then open a command line and type:


> ffmpeg -version
ffmpeg version 2021-10-07-git-b6aeee2d8b-full_build- ...

Under Test 1, the publication information can be displayed, indicating that the configuration is good.

Now read the document 1 and find that the command to split the video file is:


ffmpeg -i [filename] -ss [starttime] -t [length] -c copy [newfilename]

]

i For files that need to be cropped

ss Is the clipping start time

t Is the end time or length of clipping

c Store for cut documents

All right, write a call with Python:


import subprocess as sp
 
def cut_video(filename, outfile, start, length=90):
    cmd = "ffmpeg -i %s -ss %d -t %d -c copy %s" % (filename, start, length, outfile)
    p = sp.Popen(cmd, shell=True)
    p.wait()
    return
A function is defined, which is passed in by parameters ffmpeg Information needed Write the cropping command as a string template, and replace the parameters in it Use subprocess Adj. Popen Executes a command where the parameters shell=True Indicates that the command is executed as a whole p.wait() It is important, because the clipping takes 1 minute and is executed by another process, so you need to wait until the execution is completed before doing follow-up work, otherwise you may not find the clipped file

Then the video clipping is finished, and then we will see what is most important.

Computational segmentation

When clipping video, you need 1 parameter, especially the start time. How to determine it? If this is not done well, the cutting work will be very troublesome.

So look at how to calculate cropping segments.

I need to cut the video into one and a half minutes, so I will need to know the time length of the target video file.

Get video length

How to get the length? ffmpeg provides another command-- ffprobe .

After looking for 1, you can synthesize 1 command to get:


> ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 -i a.flv
 
920.667

Command more complex ha, can first do not care about other parameters, as long as the video file will be analyzed into the good. The result of the command is to display the length of a 1-line video file.

So you can write a function:


import subprocess as sp
 
def get_video_duration(filename):
    cmd = "ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 -i %s" % filename
    p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
    p.wait()
    strout, strerr = p.communicate() #  Remove the last carriage return 
    ret = strout.decode("utf-8").split("\n")[0]
    return ret
The function has only one parameter, which is the path of the video file Compose command statements and replace the video file path Use subprocess To execute, note that you need to set the output after the command is executed under 1 Use wait Wait for command execution to complete Pass communicate Extract the output result Extract the length of the video file from the result and return

Segment

After getting the video length and determining the length of each segment, we can calculate how many segments we need.

The code is simple:


import math
duration = math.floor(float(get_video_duration(filename)))
part = math.ceil(duration / length)

Note that when calculating segmentation, you need to round up, that is, use ceil To contain the last 1-point tail.

The required number of segments is obtained, and the starting time of each segment can be calculated in one cycle.

Get a file

Because there are many files to be processed, it is necessary to automatically obtain the files to be processed.

The method is very simple, also very commonly used, 1 can use os. walk recursive access to files, but also write their own, according to the actual situation.


for fname in os.listdir(dir):
    fname = os.path.join(dir, os.path.join(dir, fname))
    basenames = os.path.basename(fname).split('.')
    mainname = basenames[0].split("_")[0]
    ...

Provide the directory where the video files are located, and use the os.listdir Get the files in the directory, and then synthesize the absolute path of the file, because it is convenient to need an absolute path when calling the crop command.

Gets the file name in order to name the cropped file later.

Code integration

Now that every part is written, you can integrate the code:


def main(dir):
    outdir = os.path.join(dir, "output")
    if not os.path.exists(outdir):
        os.mkdir(outdir)
 
    for fname in os.listdir(dir):
        fname = os.path.join(dir, os.path.join(dir, fname))
        if os.path.isfile(fname):
            split_video(fname, outdir)
main Method is an integrated method First, create a clipped storage directory and put it in the output directory in the video file directory Pass listdir After obtaining the files, each file is processed, and whether it is a file under 1 is judged Call split_video Method to start cropping 1 video file

Summarize

Generally speaking, this is a very simple application, and its core function is to call an ffmpeg command.

Compared with technology, what is more important is how to analyze and decompose a project and where to start.

The approach here starts by looking for the most important things, pushing forward with the most important things as a clue, and finally solving the whole problem in a bottom-up way.

I hope this article will inspire you and compare your heart.

References

[1]

ffmpeg: http://ffmpeg.org/

[2]

ffmpeg Window version download: https://www.ofstack.com/softs/145521. html

The above is the python call ffmpeg command line tool convenient operation video example implementation process details, more about python call command line tool operation video information please pay attention to other related articles on this site!


Related articles: