当前位置:网站首页>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


边栏推荐
- openresty lua-resty-logger-socket日志传输
- [FPGA]: IP core - multiplier
- TwinCAT3各版本下载路径
- binlog、iptables防止nmap扫描、xtrabackup全量+增量备份以及redlog和binlog两者的关系
- Redismission watchdog implementation mechanism can be understood at a glance
- [interview: Basics 04: insert order]
- [AHK] AutoHotKey tutorial ①
- 5个最佳WordPress广告插件
- Zero basis learning canoe panel (5) -- change the value of the variable, and the control image also changes. What's going on?
- Arduino + AD9833 waveform generator
猜你喜欢

向量化引擎对HTAP的价值与技术思考

2018 arXiv | Objective-Reinforced Generative Adversarial Networks (ORGAN) for Sequence Generation Mo
![[class, abstraction and inheritance]](/img/eb/4c8d0c86b1320015b2ccb0289f4f00.png)
[class, abstraction and inheritance]

Arduino + AD9833 waveform generator
![[FPGA]: use of MicroBlaze](/img/f4/5114bf4bde10adaa22c7441350575c.png)
[FPGA]: use of MicroBlaze

实时天气API

MySQL engine

PC Museum (1) 1970 datapoint 2000

Zero basic learning canoe panel (9) -- combobox

Zero basic learning canoe panel (7) -- input/output box
随机推荐
BBR and queuing
LoRa无线技术与LoRaWAN网关模块的区别
BBR 与 queuing
App automation and simple environment construction
Cross platform audio playback Library
蓝牙模块的5大应用场景
[FPGA]: frequency measurement
MySQL engine
【直播报名】Location Cache 模块浅析及 OCP 监控、报警详解
After the QT program minimizes the tray, a msgbox pops up. Click OK and the program exits. The problem is solved
Data visualization - White Snake 2: black snake robbery (1)
Filter the data with signal processing toolbox software
[class, abstraction and inheritance]
神器 ffmpeg —— 操作视频,极度舒适
二分查找法
Detailed explanation of the implementation process of redistribution watchdog
[FPGA]: IP core -- xadc
Windows virtual machine security reinforcement process steps, detailed description of windows setting security policy, detailed description of win7 setting IP security policy, windows setting firewall
[interview: Basics 01: integer binary search]
零基础学习CANoe Panel(8)—— 数据/文本编辑控件(Hex/Text Editor )