Using Python+FFmpeg for Video Splitting and Merging
Preface Occasionally in daily life you'll run into situations that need some simple video editing. In the past I might have pulled out Premiere Pro to clip something (don't even mention those domestic Chinese apps—after you finish editing they force ads onto the beginning and end of the video, which is disgusting), but Premiere Pro is too heavyweight after all; even clipping a simple video takes quite a bit of time. Until I discovered FFmpeg... This FFmpeg is truly a godsend—free, open source, and powerful. It seems like a lot of software is built on top of it. Its command-line interface alone is already enough for our everyday simple video processing needs. I use it for simple video splitting and merging
目录7 个章节
Preface
Occasionally in daily life you'll run into situations that need some simple video editing. In the past I might have pulled out Premiere Pro to clip something (don't even mention those domestic Chinese apps—after you finish editing they force ads onto the beginning and end of the video, which is disgusting), but Premiere Pro is too heavyweight after all; even clipping a simple video takes quite a bit of time. Until I discovered FFmpeg...
This FFmpeg is truly a godsend—free, open source, and powerful. It seems like a lot of software is built on top of it. Its command-line interface alone is already enough for our everyday simple video processing needs. I use it for simple video splitting and merging, and it's really great.
Using the command line is fine for one or two files, but if you need to process multiple videos, or if the server has video processing needs (such as transcoding, adding watermarks, and the like), you need a convenient way to use FFmpeg in code. So this article will introduce seamless calling between Python and FFmpeg~
ffmpy
First, FFmpeg is an executable. To call FFmpeg from Python and monitor its status, you need to use something like os.system() or the subprocess module to create a subprocess, and you have to handle a lot of work yourself, which is rather troublesome...
The ffmpy library is what helps us solve this problem. It perfectly integrates FFmpeg and encapsulates subprocess management, so we just fill in the parameters and call it, and we're done.
Code
This article only briefly introduces how to call FFmpeg from Python. FFmpeg is very powerful; due to space limitations this article cannot cover all of FFmpeg's features one by one. Those of you who want to dive deeper into FFmpeg can check the references at the end~
Video Splitting
The example is the simplest usage of splitting a clip out of a video, and it uses the -vcodec copy -acodec copy parameters, meaning neither audio nor video is transcoded, which speeds up video processing.
Looking at the code below you'll understand the operation. Input and output are laid out crystal clear. Both inputs and outputs are dictionaries; the filename is the key, and the parameters are the value.
import ffmpy
ff = ffmpy.FFmpeg(
inputs={'input.mp4': None},
outputs={'output.mp4': [
'-ss', '00:01:20',
'-t', '02:00:00',
'-vcodec', 'copy',
'-acodec', 'copy'
]}
)
ff.run()
Before executing ff.run(), you can first use print(ff.cmd) to print the command and take a look.
The video splitting operation above corresponds to this FFmpeg command:
ffmpeg -i input.mp4 -ss 00:01:20 -t 02:00:00 -vcodec copy -acodec copy output.mp4
Video Merging
Video merging is a bit more troublesome. If you directly use an FFmpeg command with multiple video files as input and one as output, a transcoding process is required, which makes it very slow and defeats the purpose of merging.
I looked up some materials; only merging videos via a file list can concatenate without transcoding. However, this requires first creating a file to store the video list. In Python, we can achieve this by creating a temporary file.
The code is as follows:
import os
import tempfile
import ffmpy
# 创建临时文件
temp_dir = tempfile.mktemp()
os.mkdir(temp_dir)
concat_file = os.path.join(temp_dir, 'concat_list.txt')
with open(concat_file, 'w', encoding='utf-8') as f:
f.write('\n'.join([
'file C:/1.mp4',
'file C:/2.mp4',
'file C:/3.mp4',
]))
ff = ffmpy.FFmpeg(
global_options=['-f', 'concat'],
inputs={concat_file: None},
outputs={'output.mp4': ['-c', 'copy']}
)
ff.run()
Done!
References
- ffmpy official documentation: https://ffmpy-zh.readthedocs.io/zh/latest/ffmpy.html
- Generating video thumbnails with Python: https://blog.csdn.net/fei347795790/article/details/102068777
- FFMPEG video splitting and merging: https://www.jianshu.com/p/cf1e61eb6fc8
- An introductory tutorial to FFmpeg video processing: https://www.ruanyifeng.com/blog/2020/01/ffmpeg.html
Feel Free to Discuss
Programming Lab focuses on exploring popular new internet technologies and practicing team agile development. Reply with linux, flutter, c#, netcore, android, kotlin, java, python, and so on in the backend of the WeChat official account 「程序设计实验室」 to get related technical articles and materials. If you have any questions, you can also leave a message in the official account backend~
- Cnblogs: https://www.cnblogs.com/deali/
- Live coding stream: https://live.bilibili.com/11883038
- Zhihu: https://www.zhihu.com/people/dealiaxy
_EOF_
Using Python+FFmpeg for Video Splitting and Merging
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
后 Django 时代:SQLAlchemy 2.0、Tortoise 与 Piccolo 三大异步 ORM 选型指南
SQLAlchemy 2.0 才是工业级稳定,Alembic 迁移能力谁用谁知道。Tortoise ORM 是 Django 老玩家的舒适区,但灵活度有限。Piccolo 语法现代但生态太嫩,适合玩票。别再迷信 Stars,生产环境看的是谁扛造。
2026-04-10 · Python · 约 1 分钟
Python数据展示 - 生成表格图片
前言 前一篇文章介绍了推送信息到企业微信群里,其中一个项目推送的信息是使用Python自动生成的表格,本文来讲讲如何用Python生成表格图片。 选一个合适库 Python最大的优点就是第三方库丰富,基本你要什么功能,都能找到别人实现好的库,几行代码一调用就完事了。 Pytable 项目地址:https://github.com/HiroshiARAKI/pytable 最先找到的是日本人开发的p
2022-04-09 · Python · 约 1 分钟
Python-本地时间和UTC时间转换
代码 import time import datetime def utc2local(utc_st): UTC时间转本地时间(+8: 00) now_stamp = time.time() local_time = datetime.datetime.fromtimestamp(now_stamp) utc_time = datetime.datetime.ut
2021-12-18 · Python · 约 1 分钟
关于Python的异常处理
前言 异常处理在任何一门编程语言里都是值得关注的一个话题,良好的异常处理可以让你的程序更加健壮,清晰的错误信息更能帮助你快速修复问题。在Python中,和部分高级语言一样,使用了try/except/finally语句块来处理异常,如果你有其他编程语言的经验,实践起来并不难。 Python 中(至少)有两种错误:语法错误和异常( syntax errors 和 exceptions )。下面稍微介
2022-05-27 · Python · 约 1 分钟
讨论
共 0 条加载评论中…