目录
前言
环境依赖
代码
总结
前言
本文提供给视频添加背景音乐的python工具,一如既往的实用主义。
环境依赖
ffmpeg环境安装,可以参考我的另一篇文章:windows ffmpeg安装部署_阿良的博客-CSDN博客
本文主要使用到的不是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 : add_bg.py
@ide : PyCharm
@time : 2023-02-15 17:00:09
"""
import os
import uuid
from ffmpy import FFmpeg# 添加背景音
def add_bgm(video_path: str, audio_path: str, output_dir: str, duration: int):ext = os.path.basename(video_path).strip().split('.')[-1]if ext not in ['mp4', 'flv']:raise Exception('format error')ext_mp3 = os.path.basename(audio_path).strip().split('.')[-1]if ext_mp3 not in ['mp3']:raise Exception('format error')result = os.path.join(output_dir, '{}.{}'.format(uuid.uuid1().hex, ext))ff = FFmpeg(inputs={video_path: None, audio_path: None},outputs={result: r'-ac 1 -acodec aac -ar 48000 -filter_complex [1]volume=0.13[vo1];[''vo1]aloop=loop=-1:size=2e+09[ao1];[ao1]atrim=0:{}[ap1];[ap1]adelay=0|0[a1];[a1][''0:a]amix=2:dropout_transition={} -g 30 -keyint_min 30 -level 3.1 -preset:v medium ''-profile:v baseline -sc_threshold 0 -vcodec libx264'.format(duration, duration * 100)})print(ff.cmd)ff.run()return resultif __name__ == '__main__':print(add_bgm(r'E:\360MoveData\Users\xxx\Desktop\movie.mp4', r'E:\360MoveData\Users\xxx\Desktop\1.mp3',r'E:\360MoveData\Users\xxx\Desktop', 300))
代码说明
1、add_bgm方法参数分别为,输入视频地址、输入音频地址、输出目录地址、音频时长。
2、做了简单的视频格式校验,如需添加,可以自己看着来。
3、最终视频名使用uuid避免重复。
4、音频会在视频中循环,如果要选定一些时间区域出现背景音乐的话可以自行调整一下命令参数。
验证一下
准备的视频和背景音乐信息。
执行结果
ffmpeg -i E:\360MoveData\Users\xxx\Desktop\movie.mp4 -i E:\360MoveData\Users\xxx\Desktop\1.mp3 -ac 1 -acodec aac -ar 48000 -filter_complex [1]volume=0.13[vo1];[vo1]aloop=loop=-1:size=2e+09[ao1];[ao1]atrim=0:300[ap1];[ap1]adelay=0|0[a1];[a1][0:a]amix=2:dropout_transition=30000 -g 30 -keyint_min 30 -level 3.1 -preset:v medium -profile:v baseline -sc_threshold 0 -vcodec libx264 E:\360MoveData\Users\huyi\Desktop\6295a1daaea811eda363e454e8bf1461.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
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'E:\360MoveData\Users\huyi\Desktop\movie.mp4':
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf58.45.100
Duration: 00:05:00.18, start: 0.000000, bitrate: 2447 kb/s
Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 2321 kb/s, 23.98 fps, 23.98 tbr, 24k tbn, 47.95 tbc (default)
Metadata:
handler_name : VideoHandler
Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 120 kb/s (default)
Metadata:
handler_name : SoundHandler
Input #1, mp3, from 'E:\360MoveData\Users\huyi\Desktop\1.mp3':
Metadata:
time_reference : 0
creation_time : 2023-01-17T04:11:04.000000Z
encoder : Lavf59.34.101
date : 2022-01-12
Duration: 00:00:10.25, start: 0.023021, bitrate: 320 kb/s
Stream #1:0: Audio: mp3, 48000 Hz, mono, fltp, 320 kb/s
Stream mapping:
Stream #0:1 (aac) -> amix:input1 (graph 0)
Stream #1:0 (mp3float) -> volume (graph 0)
amix (graph 0) -> Stream #0:0 (aac)
Stream #0:0 -> #0:1 (h264 (native) -> h264 (libx264))
Press [q] to stop, [?] for help
[libx264 @ 0000021a30adbf00] using SAR=1/1
[libx264 @ 0000021a30adbf00] frame MB size (120x68) > level limit (3600)
[libx264 @ 0000021a30adbf00] MB rate (195644) > level limit (108000)
[libx264 @ 0000021a30adbf00] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
[libx264 @ 0000021a30adbf00] profile Constrained Baseline, level 3.1, 4:2:0, 8-bit
[libx264 @ 0000021a30adbf00] 264 - core 161 - H.264/MPEG-4 AVC codec - Copyleft 2003-2020 - http://www.videolan.org/x264.html - options: cabac=0 ref=2 deblock=1:0:0 analyse=0x1:0x111 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=0 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=9 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=0 weightp=0 keyint=30 keyint_min=16 scenecut=0 intra_refresh=0 rc_lookahead=30 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mp4, to 'E:\360MoveData\Users\huyi\Desktop\6295a1daaea811eda363e454e8bf1461.mp4':
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf58.45.100
Stream #0:0: Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, mono, fltp, 69 kb/s (default)
Metadata:
encoder : Lavc58.91.100 aac
Stream #0:1(und): Video: h264 (libx264) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], q=-1--1, 23.98 fps, 24k tbn, 23.98 tbc (default)
Metadata:
handler_name : VideoHandler
encoder : Lavc58.91.100 libx264
Side data:
cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: N/A
frame= 7197 fps= 79 q=-1.0 Lsize= 136079kB time=00:05:00.13 bitrate=3714.2kbits/s speed=3.29x
video:133403kB audio:2527kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.109709%
[aac @ 0000021a30adaac0] Qavg: 1648.401
[libx264 @ 0000021a30adbf00] frame I:240 Avg QP:15.95 size:145845
[libx264 @ 0000021a30adbf00] frame P:6957 Avg QP:19.64 size: 14604
[libx264 @ 0000021a30adbf00] mb I I16..4: 43.8% 0.0% 56.2%
[libx264 @ 0000021a30adbf00] mb P I16..4: 4.8% 0.0% 1.1% P16..4: 28.3% 5.8% 1.6% 0.0% 0.0% skip:58.4%
[libx264 @ 0000021a30adbf00] coded y,uvDC,uvAC intra: 28.9% 51.9% 14.9% inter: 6.0% 15.3% 0.1%
[libx264 @ 0000021a30adbf00] i16 v,h,dc,p: 47% 23% 15% 15%
[libx264 @ 0000021a30adbf00] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 22% 22% 18% 6% 8% 5% 7% 5% 6%
[libx264 @ 0000021a30adbf00] i8c dc,h,v,p: 61% 18% 17% 4%
[libx264 @ 0000021a30adbf00] ref P L0: 77.2% 22.8%
[libx264 @ 0000021a30adbf00] kb/s:3640.66
E:\360MoveData\Users\xxx\Desktop\6295a1daaea811eda363e454e8bf1461.mp4
结果视频信息
总结
没啥好总结的,正好用到了就分享下,大家用的时候看着改。
分享今天的心情:
最近所有的人工智能板块热点都在chatgpt,让我产生了很强烈的不安全感。很多时候资本能帮助一个新的东西更快的让人了解和接受,但过度的捧杀也会让一个东西消逝的太快。期待下个版本能继续带给人的惊喜,赋予一些互联网传统行业更强的交互能力和落地场景。
如果本文对你有帮助的话,点个赞吧,谢谢!