Python實現(xiàn)多個視頻合成一個視頻的功能
前言
本文提供將多個視頻拼接為一個視頻的Python工具代碼,其中有一些限制條件,下面的代碼說明會提到。
環(huán)境依賴
ffmpeg環(huán)境安裝,可以參考:windows ffmpeg安裝部署
本文主要使用到的不是ffmpeg,而是ffprobe也在上面這篇文章中的zip包中。
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 # 構(gòu)造拼接所需臨時文件 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 執(zhí)行結(jié)果: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,入?yún)⒎謩e為:視頻列表、輸出目錄。
2、該視頻拼接命令對視頻本身有所限制,需要保證都是相同格式的視頻,其次是每個視頻的fps得一致,不然最終合成的視頻會無法打開或者出現(xiàn)花屏現(xiàn)象。
3、臨時的拼接文件會在使用后刪除。
4、最終輸出的文件名為了保證唯一使用uuid。
驗證一下
下面是我準(zhǔn)備的兩個視頻:
執(zhí)行結(jié)果
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 執(zhí)行結(jié)果:out:b'25/1\r\n' err:b'' subprocess 執(zhí)行結(jié)果: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
結(jié)果驗證
到此這篇關(guān)于Python實現(xiàn)多個視頻合成一個視頻的功能的文章就介紹到這了,更多相關(guān)Python視頻合成內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3 常見解密加密算法實例分析【base64、MD5等】
這篇文章主要介紹了python3 常見解密加密算法,結(jié)合實例形式分析了Python的base64模塊加密,以及基于pycrypto模塊的MD5加密等相關(guān)操作技巧,需要的朋友可以參考下2019-12-12Python使用LSTM實現(xiàn)銷售額預(yù)測詳解
大家經(jīng)常會遇到一些需要預(yù)測的場景,比如預(yù)測品牌銷售額,預(yù)測產(chǎn)品銷量。本文給大家分享一波使用?LSTM?進(jìn)行端到端時間序列預(yù)測的完整代碼和詳細(xì)解釋,需要的可以參考一下2022-07-07Python與xlwings黃金組合處理Excel各種數(shù)據(jù)和自動化任務(wù)
這篇文章主要為大家介紹了Python與xlwings黃金組合處理Excel各種數(shù)據(jù)和自動化任務(wù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪<BR>2023-12-12Python中MySQL數(shù)據(jù)遷移到MongoDB腳本的方法
MongoDB 是一個介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫當(dāng)中功能最豐富,最像關(guān)系數(shù)據(jù)庫的。本文給大家介紹Python中MySQL數(shù)據(jù)遷移到MongoDB腳本的方法,需要的朋友參考下2016-04-04Python爬蟲學(xué)習(xí)之requests的使用教程
requests庫是一個常用的用于?http?請求的模塊,它使用?python?語言編寫,可以方便的對網(wǎng)頁進(jìn)行爬取。本文將通過示例詳細(xì)講講requests庫的使用,需要的可以參考一下2022-08-08