Python 多个视频拼接成一个视频工具(附代码) | Python工具

简介: Python 多个视频拼接成一个视频工具(附代码) | Python工具

前言

本文提供将多个视频拼接为一个视频的Python工具代码,其中有一些限制条件,下面的代码说明会提到。


环境依赖

 ffmpeg环境安装,可以参考我的另一篇文章:windows ffmpeg安装部署_阿良的博客-CSDN博客


本文主要使用到的不是ffmpeg,而是ffprobe也在上面这篇文章中的zip包中。

image.png



ffmpy安装:


pip install ffmpy -i https://pypi.douban.com/simple

代码

不废话了,上代码。

#!/user/bin/env python
# coding=utf-8
"""
@project : csdn
@author  : 剑客阿良_ALiang
@file   : concat_video.py
@ide    : PyCharm
@time   : 2021-12-23 15:23:16
"""
from ffmpy import FFmpeg
import os
import uuid
import subprocess
# 视频拼接
def concat(video_list: list, output_dir: str):
    if len(video_list) == 0:
        raise Exception('video_list can not empty')
    _ext = check_format(video_list)
    _fps = check_fps(video_list)
    _result_path = os.path.join(
        output_dir, '{}{}'.format(
            uuid.uuid1().hex, _ext))
    _tmp_config = make_tmp_concat_config(video_list, output_dir)
    ff = FFmpeg(inputs={'{}'.format(_tmp_config): '-f concat -safe 0 -y'}, outputs={
        _result_path: '-c copy'})
    print(ff.cmd)
    ff.run()
    os.remove(_tmp_config)
    return _result_path
# 构造拼接所需临时文件
def make_tmp_concat_config(video_list: list, output_dir: str):
    _tmp_concat_config_path = os.path.join(output_dir, '{}.txt'.format(uuid.uuid1().hex))
    with open(_tmp_concat_config_path, mode='w', encoding='utf-8') as f:
        f.writelines(list(map(lambda x: 'file {}\n'.format(x), video_list)))
    return _tmp_concat_config_path
# 校验每个视频的格式
def check_format(video_list: list):
    _video_format = ''
    for x in video_list:
        _ext = os.path.splitext(x)[-1]
        if _video_format == '' and _ext != '':
            _video_format = _ext
            continue
        if _video_format != '' and _ext == _video_format:
            continue
        if _video_format != '' and _ext != _video_format:
            raise Exception('Inconsistent video format')
    return _video_format
# 校验每个视频的fps
def check_fps(video_list: list):
    _video_fps = 0
    for x in video_list:
        _fps = get_video_fps(x)
        if _video_fps == 0 and _fps:
            _video_fps = _fps
            continue
        if _video_fps != 0 and _fps == _video_fps:
            continue
        if _video_fps != '' and _fps != _video_fps:
            raise Exception('Inconsistent video fps')
    if _video_fps == 0:
        raise Exception('video fps error')
    return _video_fps
# 获取视频fps
def get_video_fps(video_path: str):
    ext = os.path.splitext(video_path)[-1]
    if ext != '.mp4' and ext != '.avi' and ext != '.flv':
        raise Exception('format not support')
    ffprobe_cmd = 'ffprobe -v error -select_streams v -of default=noprint_wrappers=1:nokey=1 -show_entries stream=r_frame_rate {}'
    p = subprocess.Popen(
        ffprobe_cmd.format(video_path),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True)
    out, err = p.communicate()
    print("subprocess 执行结果:out:{} err:{}".format(out, err))
    fps_info = str(out, 'utf-8').strip()
    if fps_info:
        if fps_info.find("/") > 0:
            video_fps_str = fps_info.split('/', 1)
            fps_result = int(int(video_fps_str[0]) / int(video_fps_str[1]))
        else:
            fps_result = int(fps_info)
    else:
        raise Exception('get fps error')
    return fps_result
if __name__ == '__main__':
    print(concat(['D:/tmp/100.mp4', 'D:/tmp/101.mp4'], 'C:/Users/huyi/Desktop'))


代码说明


1、主要拼接方法为concat,入参分别为:视频列表、输出目录。


2、该视频拼接命令对视频本身有所限制,需要保证都是相同格式的视频,其次是每个视频的fps得一致,不然最终合成的视频会无法打开或者出现花屏现象。


3、临时的拼接文件会在使用后删除。


4、最终输出的文件名为了保证唯一使用uuid。


验证一下


下面是我准备的两个视频:


image.png


执行结果

PyDev console: starting.
Python 3.6.13 |Anaconda, Inc.| (default, Mar 16 2021, 11:37:27) [MSC v.1916 64 bit (AMD64)] on win32
runfile('D:/spyder/csdn/tool/concat_video.py', wdir='D:/spyder/csdn/tool')
subprocess 执行结果:out:b'25/1\r\n' err:b''
subprocess 执行结果:out:b'25/1\r\n' err:b''
ffmpeg -f concat -safe 0 -y -i C:/Users/huyi/Desktop\6d02df4b63d111eca6eee454e8bf1461.txt -c copy C:/Users/huyi/Desktop\6d02df4a63d111ec9dbbe454e8bf1461.mp4
ffmpeg version n4.3.1-20-g8a2acdc6da Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.3-win32 (GCC) 20200320
  configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvmaf --disable-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
[mov,mp4,m4a,3gp,3g2,mj2 @ 000001de4a7aebc0] Auto-inserting h264_mp4toannexb bitstream filter
Input #0, concat, from 'C:/Users/huyi/Desktop\6d02df4b63d111eca6eee454e8bf1461.txt':
  Duration: N/A, start: -0.064000, bitrate: 1098 kb/s
    Stream #0:0(und): Audio: aac (LC) (mp4a / 0x6134706D), 16000 Hz, mono, fltp, 69 kb/s
    Metadata:
      handler_name    : SoundHandler
    Stream #0:1(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p, 1080x1920, 1028 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc
    Metadata:
      handler_name    : VideoHandler
Output #0, mp4, to 'C:/Users/huyi/Desktop\6d02df4a63d111ec9dbbe454e8bf1461.mp4':
  Metadata:
    encoder         : Lavf58.45.100
    Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p, 1080x1920, q=2-31, 1028 kb/s, 25 fps, 25 tbr, 12800 tbn, 12800 tbc
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 16000 Hz, mono, fltp, 69 kb/s
    Metadata:
      handler_name    : SoundHandler
Stream mapping:
  Stream #0:1 -> #0:0 (copy)
  Stream #0:0 -> #0:1 (copy)
Press [q] to stop, [?] for help
[mov,mp4,m4a,3gp,3g2,mj2 @ 000001de4a7aebc0] Auto-inserting h264_mp4toannexb bitstream filter
[mp4 @ 000001de4acdabc0] Non-monotonous DTS in output stream 0:1; previous: 6176768, current: 6176608; changing to 6176769. This may result in incorrect timestamps in the output file.
frame=22199 fps=0.0 q=-1.0 Lsize=  119649kB time=00:14:48.05 bitrate=1103.7kbits/s speed=2.41e+03x    
video:111571kB audio:7524kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.465183%
C:/Users/huyi/Desktop\6d02df4a63d111ec9dbbe454e8bf1461.mp4


结果验证

image.png

总结

视频拼接的限制还是有点多的。

相关文章
|
人工智能 Python
Python工具:将文件夹下的视频按照帧数输出图片文件(含代码)
Python工具:将文件夹下的视频按照帧数输出图片文件(含代码)
169 0
|
机器学习/深度学习 数据处理 算法框架/工具
|
23天前
|
存储 缓存 Java
Python高性能编程:五种核心优化技术的原理与Python代码
Python在高性能应用场景中常因执行速度不及C、C++等编译型语言而受质疑,但通过合理利用标准库的优化特性,如`__slots__`机制、列表推导式、`@lru_cache`装饰器和生成器等,可以显著提升代码效率。本文详细介绍了这些实用的性能优化技术,帮助开发者在不牺牲代码质量的前提下提高程序性能。实验数据表明,这些优化方法能在内存使用和计算效率方面带来显著改进,适用于大规模数据处理、递归计算等场景。
58 5
Python高性能编程:五种核心优化技术的原理与Python代码
|
2月前
|
Python
[oeasy]python055_python编程_容易出现的问题_函数名的重新赋值_print_int
本文介绍了Python编程中容易出现的问题,特别是函数名、类名和模块名的重新赋值。通过具体示例展示了将内建函数(如`print`、`int`、`max`)或模块名(如`os`)重新赋值为其他类型后,会导致原有功能失效。例如,将`print`赋值为整数后,无法再用其输出内容;将`int`赋值为整数后,无法再进行类型转换。重新赋值后,这些名称失去了原有的功能,可能导致程序错误。总结指出,已有的函数名、类名和模块名不适合覆盖赋新值,否则会失去原有功能。如果需要使用类似的变量名,建议采用其他命名方式以避免冲突。
52 14
|
2月前
|
分布式计算 大数据 数据处理
技术评测:MaxCompute MaxFrame——阿里云自研分布式计算框架的Python编程接口
随着大数据和人工智能技术的发展,数据处理的需求日益增长。阿里云推出的MaxCompute MaxFrame(简称“MaxFrame”)是一个专为Python开发者设计的分布式计算框架,它不仅支持Python编程接口,还能直接利用MaxCompute的云原生大数据计算资源和服务。本文将通过一系列最佳实践测评,探讨MaxFrame在分布式Pandas处理以及大语言模型数据处理场景中的表现,并分析其在实际工作中的应用潜力。
116 2
|
2月前
|
Unix Linux 程序员
[oeasy]python053_学编程为什么从hello_world_开始
视频介绍了“Hello World”程序的由来及其在编程中的重要性。从贝尔实验室诞生的Unix系统和C语言说起,讲述了“Hello World”作为经典示例的起源和流传过程。文章还探讨了C语言对其他编程语言的影响,以及它在系统编程中的地位。最后总结了“Hello World”、print、小括号和双引号等编程概念的来源。
126 80
|
2月前
|
存储 数据采集 人工智能
Python编程入门:从零基础到实战应用
本文是一篇面向初学者的Python编程教程,旨在帮助读者从零开始学习Python编程语言。文章首先介绍了Python的基本概念和特点,然后通过一个简单的例子展示了如何编写Python代码。接下来,文章详细介绍了Python的数据类型、变量、运算符、控制结构、函数等基本语法知识。最后,文章通过一个实战项目——制作一个简单的计算器程序,帮助读者巩固所学知识并提高编程技能。
|
2月前
|
人工智能 数据挖掘 开发者
探索Python编程之美:从基础到进阶
本文是一篇深入浅出的Python编程指南,旨在帮助初学者理解Python编程的核心概念,并引导他们逐步掌握更高级的技术。文章不仅涵盖了Python的基础语法,还深入探讨了面向对象编程、函数式编程等高级主题。通过丰富的代码示例和实践项目,读者将能够巩固所学知识,提升编程技能。无论你是编程新手还是有一定经验的开发者,这篇文章都将为你提供有价值的参考和启示。让我们一起踏上Python编程的美妙旅程吧!
|
2月前
|
小程序 开发者 Python
探索Python编程:从基础到实战
本文将引导你走进Python编程的世界,从基础语法开始,逐步深入到实战项目。我们将一起探讨如何在编程中发挥创意,解决问题,并分享一些实用的技巧和心得。无论你是编程新手还是有一定经验的开发者,这篇文章都将为你提供有价值的参考。让我们一起开启Python编程的探索之旅吧!
65 10

热门文章

最新文章

推荐镜像

更多