当前位置:网站首页>Artifact ffmpeg - operation video, extremely comfortable
Artifact ffmpeg - operation video, extremely comfortable
2022-07-24 10:56:00 【The way of Python data】
source :Python technology 「ID: pythonall」

Recently, I have a new task , The event video needs to be , Split into small segments within two minutes , For publishing to short video platform .
I thought it was a one-time job , As a result, the video data of the event is huge , Video files vary in length , It's totally impossible to handle it by hand , therefore Python Saved me again .
What are we waiting for? , Let's get started !
The most important thing
Whatever you do , We have to analyze what is the most important , Then concentrate on conquering , Keep looking for the most important thing .
For our mission , It's not a big project , But what? , Or start with the most important thing , Advance gradually and entrench oneself at every step , Finally, the whole problem was solved .
On the whole , We need to read video files from a directory , then , Clip each video file , Finally, save the processed files .
In the process , What's the most important thing ? I think , It's video clipping , If you can't easily cut the video , Everything else is in vain , Is that so? .
Clip video
Short videos are very popular now , There are many video editing software , Rich in functions , All we need is the clipping function , And you need to call... Programmatically , Then the most appropriate is ffmpeg[1] 了 .
ffmpeg Is a command line tool , Powerful , You can programmatically call .
from ffmpeg Download the version of the corresponding operating system on the official website , What I'm doing is Windows edition [2].
Download and unzip to a directory , Then put the... In the directory bin, Configure to environment variables . Then open a command line , Input :
> ffmpeg -version
ffmpeg version 2021-10-07-git-b6aeee2d8b-full_build- ...Test it , Can display version information , It indicates that the configuration is ready .
Now read the document , The command found to split video files is :
ffmpeg -i [filename] -ss [starttime] -t [length] -c copy [newfilename]iFor files that need to be croppedssIs the start time of clippingtIs the end time or length of clippingcStore for cut files
Okay , use Python Write a call :
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()
returnDefines a function , Passed in by parameter
ffmpegInformation neededWrite the clipping command as a string template , Replace the parameter with
use
subprocessOfPopenCarry out orders , The parametershell=TrueMeans to execute the command as a wholep.wait()Very important , Because cutting takes a while , And it is executed by another process , So we need to wait until the implementation is completed before we do the follow-up work , Otherwise, the cropped file may not be found
In this way, the video clipping work is completed , Then look at what is most important .
Calculation segment
Video clipping , You need some parameters , Especially the start time , How to make sure ? If you can't do it well , Cutting is troublesome .
So let's see how to calculate clipping segments .
I need to cut the video into one and a half segments , Then you will need to know the length of time of the target video file .
Get video length
How to get the length ?ffmpeg Another command is provided —— ffprobe.
To find the , You can synthesize a command to get :
> ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 -i a.flv
920.667The command is complicated , You can ignore other parameters , Just import the video file to be analyzed . The result of the command is to display the length of a line of 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 retThe function has only one argument , Is the path of the video file
Composite command statement , Replace the video file path
use
subprocessTo execute , Note that you need to set the output after the command is executeduse
waitWait for the command execution to completeadopt
communicateExtract output resultsExtract the length of the video file from the result , return
piecewise
Get the video length , Determine the length of each segment , You can calculate how many segments are needed .
The code is simple :
import math
duration = math.floor(float(get_video_duration(filename)))
part = math.ceil(duration / length) Be careful , When calculating segments , Need to round up , The box ceil, To contain the last point of the tail .
The required number of segments is obtained , The starting time of each section can be calculated with one cycle .
get files
Because a lot of files are processed , Therefore, it is necessary to automatically obtain the files to be processed .
It's easy , Also very common , It can be used in general os.walk Get files recursively , You can also write by yourself , 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 file is located , adopt os.listdir Get the files in the directory , then , The absolute path of the composite file , Because it is more convenient to call the clipping command with absolute path .
Get the file name , Is to name the cropped file later .
Code integration
Now 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)mainMethod is the integrated methodFirst create a trimmed storage directory , In the video file directory output Directory
adopt
listdirAfter getting the file , Process each file , Which determines whether it is a filecall
split_videoMethod starts clipping a video file
summary
Overall speaking , This is a very simple application , The core function is to call a ffmpeg command .
Relative to technology , More importantly, how to analyze and decompose a project , And where to start .
The way here starts with , Keep looking for the most important things , Keep moving forward with the most important things as clues , Finally solve the whole problem from bottom to top .
I hope this article will inspire you , finger heart .
Reference material
[1]
ffmpeg: http://ffmpeg.org/
[2]ffmpeg Window Download version : https://www.gyan.dev/ffmpeg/builds/packages/ffmpeg-2021-10-14-git-c336c7a9d7-full_build.7z
-------- End --------

Selected content
The illustration Pandas- Image & Text 01- Data structure introduction
The illustration Pandas- Image & Text 02- Create data objects
The illustration Pandas- Image & Text 03- Read and store Excel file
The illustration Pandas- Image & Text 04- Common data access
The illustration Pandas- Image & Text 05- Common data operations
The illustration Pandas- Image & Text 06- Common mathematical calculations
The illustration Pandas- Image & Text 08- Common data filtering


边栏推荐
- Activity review | Anyuan AI X machine heart series lecture No. 1 | deepmind research scientist rohin Shah shares "finding a safe path for AgI"
- [interview: Basics 05: quick sort]
- 零基础学习CANoe Panel(4)——按钮(Button )
- 零基础学习CANoe Panel(9)—— 组合框(ComboBox)
- Five application scenarios of Bluetooth module
- Tidb query SQL report runtime error: index out of range [-1] error
- QT create application tray and related functions
- [class, abstraction and inheritance]
- Zero basis learning canoe panel (5) -- change the value of the variable, and the control image also changes. What's going on?
- 小熊派学习——内核开发
猜你喜欢

机器学习小试(10)使用Qt与Tensorflow创建CNN/FNN测试环境

【直播报名】Location Cache 模块浅析及 OCP 监控、报警详解

App automation and simple environment construction

Zero basic learning canoe panel (6) -- switch/indicator

Simply use MySQL index

PC Museum (1) 1970 datapoint 2000

Distributed transaction processing scheme big PK!

QT create application tray and related functions

Zero basic learning canoe panel (7) -- file selection (pathdiaglog)

轻松读懂三极管,原来它是这样工作的
随机推荐
Problem solving -- question 283 of leetcode question bank
跨平台音频播放库
题解——Leetcode题库第283题
[FPGA]: use of MicroBlaze
MySQL engine
变频器的工作原理和功能应用
[about Modelsim simulation] design and Simulation of 4-bit counter
对话ACE第四期:分布式数据库未来发展的挑战和机遇
[dish of learning notes, dog learning C] minesweeping game
「低功耗蓝牙模块」主从一体 蓝牙嗅探-助力智能门锁
LoRa无线技术与LoRaWAN网关模块的区别
[FPGA]: IP core ibert
[dish of learning notes dog learning C] detailed operator
PC博物馆(1) 1970年 Datapoint 2000
web咸鱼自救攻略--typescript的类没有你想象中的那么难
Redismission watchdog implementation mechanism can be understood at a glance
JS tree structure, find out the parent set of each layer it belongs to according to the ID of the inner layer
[FPGA]: IP core -- xadc
每日三题 7.21
rs485通信OSI模型网络层