目录
前言
环境依赖
代码
总结
前言
本文提供给视频添加背景音乐,一如既往的实用主义。
主要也是学习一下golang使用ffmpeg工具的方式。
环境依赖
ffmpeg环境安装,可以参考我的另一篇文章:windows ffmpeg安装部署_阿良的博客-CSDN博客
本文主要使用到的不是ffmpeg,而是ffprobe也在上面这篇文章中的zip包中。
golang主要依赖库
github.com/u2takey/ffmpeg-go
代码
不废话,上代码。下面为功能实现的主要代码。
package mainimport (logutil "csdn/utils""fmt""github.com/gofrs/uuid""github.com/google/logger"ffmpeg "github.com/u2takey/ffmpeg-go""path/filepath""strings"
)func InFormat2(target string, str_array []string) bool {for _, element := range str_array {if target == element {return true}}return false
}//视频添加背景音
func AddBgm(inputVideoPath, inputAudioPath, outputDir string, duration int) string {_videoFormatArr := []string{"mp4", "flv"}_audioFormatArr := []string{"mp3"}_, _file := filepath.Split(inputVideoPath)_tmps := strings.Split(_file, ".")_videoExt := _tmps[len(_tmps)-1]if !InFormat2(_videoExt, _videoFormatArr) {logger.Fatal("视频格式不支持")}_, _file = filepath.Split(inputAudioPath)_tmps = strings.Split(_file, ".")_audioExt := _tmps[len(_tmps)-1]if !InFormat2(_audioExt, _audioFormatArr) {logger.Fatal("音频格式不支持")}_name, err := uuid.NewV4()if err != nil {logger.Fatal(err)}_resultVideoPath := filepath.Join(outputDir, fmt.Sprintf("%s.%s", _name.String(), _videoExt))err = ffmpeg.Input(inputAudioPath, ffmpeg.KwArgs{"i": inputVideoPath}).Output(_resultVideoPath, ffmpeg.KwArgs{"filter_complex": fmt.Sprintf("[1]volume=0.13[vo1];[vo1]aloop=loop=-1:size=2e+09[ao1];[ao1]atrim=0:%d[ap1];[ap1]adelay=0|0[a1];[a1][0:a]amix=2:dropout_transition=%d", duration, duration*100), "acodec": "aac", "ar": "48000", "ac": "1", "vcodec": "libx264", "profile:v": "baseline", "level": "3.1", "preset:v": "medium", "g": "30", "keyint_min": "30", "sc_threshold": "0"}).OverWriteOutput().ErrorToStdOut().Run()if err != nil {logger.Fatal(err)}return _resultVideoPath
}func main() {logutil.Init(true, false, "1.log")defer logutil.Close()_result := AddBgm("E:\\360MoveData\\Users\\xxx\\Desktop\\movie.mp4", "E:\\360MoveData\\Users\\xxx\\Desktop\\1.mp3", "E:\\360MoveData\\Users\\xxx\\Desktop", 300)fmt.Println(_result)
}
日志工具代码如下,非必要。
package logutilimport ("github.com/google/logger""os"
)var pLogger *logger.Logger// Init init logger
func Init(verbose, systemLog bool, logPath string) {file, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)if err != nil {logger.Fatalf("logger Init: open log file(%v) error(%v)", logPath, err)}pLogger = logger.Init("FFmpegDemoLogger", verbose, systemLog, file)
}// Close close logger
func Close() {pLogger.Close()
}
代码说明
1、AddBgm方法参数分别为,输入视频地址、输入音频地址、输出目录地址、音频时长。
2、做了简单的视频格式校验,如需添加,可以自己看着来。
3、最终视频名使用uuid避免重复。
4、音频会在视频中循环,如果要选定一些时间区域出现背景音乐的话可以自行调整一下命令参数。
验证一下
准备的视频和背景音乐信息。
执行结果
2023/02/14 18:20:19 compiled command: ffmpeg -i E:\360MoveData\Users\huyi\Desktop\movie.mp4 -i E:\360MoveData\Users\huyi\Desktop\1.mp3 -ac 1 -acodec aac -ar 48000 -filter_complex [1]v
olume=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\5c389bbe-f531-440e-8e87-c0cbddae5da7.mp4 -y
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 --enabl
e-version3 --disable-debug --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvmaf --dis
able-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-lib
bluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenj
peg --enable-librav1e --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxvid --ena
ble-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 @ 0000015d0ccfb840] using SAR=1/1
[libx264 @ 0000015d0ccfb840] frame MB size (120x68) > level limit (3600)
[libx264 @ 0000015d0ccfb840] MB rate (195644) > level limit (108000)
[libx264 @ 0000015d0ccfb840] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
[libx264 @ 0000015d0ccfb840] profile Constrained Baseline, level 3.1, 4:2:0, 8-bit
[libx264 @ 0000015d0ccfb840] 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\5c389bbe-f531-440e-8e87-c0cbddae5da7.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= 80 q=-1.0 Lsize= 136079kB time=00:05:00.13 bitrate=3714.2kbits/s speed=3.35x
video:133403kB audio:2527kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.109709%
[aac @ 0000015d0c66eb80] Qavg: 1648.401
[libx264 @ 0000015d0ccfb840] frame I:240 Avg QP:15.95 size:145845
[libx264 @ 0000015d0ccfb840] frame P:6957 Avg QP:19.64 size: 14604
[libx264 @ 0000015d0ccfb840] mb I I16..4: 43.8% 0.0% 56.2%
[libx264 @ 0000015d0ccfb840] 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 @ 0000015d0ccfb840] coded y,uvDC,uvAC intra: 28.9% 51.9% 14.9% inter: 6.0% 15.3% 0.1%
[libx264 @ 0000015d0ccfb840] i16 v,h,dc,p: 47% 23% 15% 15%
[libx264 @ 0000015d0ccfb840] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 22% 22% 18% 6% 8% 5% 7% 5% 6%
[libx264 @ 0000015d0ccfb840] i8c dc,h,v,p: 61% 18% 17% 4%
[libx264 @ 0000015d0ccfb840] ref P L0: 77.2% 22.8%
[libx264 @ 0000015d0ccfb840] kb/s:3640.66
E:\360MoveData\Users\huyi\Desktop\5c389bbe-f531-440e-8e87-c0cbddae5da7.mp4
结果视频信息
总结
没啥好总结的,正好用到了就分享下,大家用的时候看着改。
分享:
想要永恒的人会看天空,想要瞬间的人会看云朵。
如果本文对你有帮助的话,点个赞吧,谢谢!