赞
踩
目录
本文提供给视频添加背景音乐的java工具,一如既往的实用主义。
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>30.1.1-jre</version>
- </dependency>
- <dependency>
- <groupId>org.bytedeco</groupId>
- <artifactId>javacv-platform</artifactId>
- <version>1.5.5</version>
- </dependency>
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-all</artifactId>
- <version>5.5.2</version>
- </dependency>
ffmpeg环境安装,可以参考我的另一篇文章:windows ffmpeg安装部署_阿良的博客-CSDN博客
本文主要使用到的不是ffmpeg,而是ffprobe也在上面这篇文章中的zip包中。
不废话,上代码。下面为功能实现的主要代码。
- package ai.guiji.csdn.tools;
-
- import cn.hutool.core.util.IdUtil;
- import com.google.common.base.Joiner;
- import com.google.common.base.Splitter;
-
- import java.io.File;
- import java.text.MessageFormat;
- import java.util.Arrays;
- import java.util.List;
-
- /** @Author 剑客阿良_ALiang @Date 2023/2/20 19:31 @Description: 视频增加背景音乐 */
- public class AddBgmUtils {
- /**
- * 视频增加背景音乐
- *
- * @param videoPath 视频地址
- * @param audioPath 音频地址
- * @param outputDir 输出目录
- * @param duration 视频时长
- * @return 结果视频地址
- */
- public static String addBgm(
- String videoPath, String audioPath, String outputDir, Integer duration) throws Exception {
- List<String> videoPaths = Splitter.on(".").splitToList(videoPath);
- String videoExt = videoPaths.get(videoPaths.size() - 1);
- if (!Arrays.asList("mp4", "flv", "avi").contains(videoExt)) {
- throw new Exception("format error");
- }
- List<String> audioPaths = Splitter.on(".").splitToList(audioPath);
- String audioExt = audioPaths.get(audioPaths.size() - 1);
- if (!Arrays.asList("mp3").contains(audioExt)) {
- throw new Exception("format error");
- }
- String resultPath =
- Joiner.on(File.separator)
- .join(Arrays.asList(outputDir, IdUtil.simpleUUID() + "." + videoExt));
- ProcessBuilder builder =
- new ProcessBuilder(
- "C:\\ffpg\\bin\\ffmpeg.exe",
- "-i",
- videoPath,
- "-i",
- audioPath,
- "-ac",
- "1",
- "-acodec",
- "aac",
- "-ar",
- "48000",
- "-filter_complex",
- MessageFormat.format(
- "[1]volume=0.13[vo1];[vo1]aloop=loop=-1:size=2e+09[ao1];[ao1]atrim=0:{0}[ap1];[ap1]adelay=0|0[a1];[a1][0:a]amix=2:dropout_transition={1}",
- String.valueOf(duration), String.valueOf(100 * duration)),
- "-g",
- "30",
- "-keyint_min",
- "30",
- "-level",
- "3.1",
- "-preset:v",
- "medium",
- "-profile:v",
- "baseline",
- "-sc_threshold",
- "0",
- "-vcodec",
- "libx264",
- resultPath);
- builder.inheritIO().start().waitFor();
- return resultPath;
- }
-
- public static void main(String[] args) throws Exception {
- System.out.println(
- addBgm(
- "E:\\360MoveData\\Users\\xxx\\Desktop\\movie.mp4",
- "E:\\360MoveData\\Users\\xxx\\Desktop\\1.mp3",
- "E:\\360MoveData\\Users\\xxx\\Desktop",
- 300));
- }
- }
代码说明
1、addBgm方法参数分别为,输入视频地址、输入音频地址、输出目录地址、音频时长。
2、做了简单的视频格式校验,如需添加,可以自己看着来。
3、最终视频名使用uuid避免重复。
4、音频会在视频中循环,如果要选定一些时间区域出现背景音乐的话可以自行调整一下命令参数。
验证一下
准备的视频和背景音乐信息。
执行结果
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 @ 0000027bcea8bd80] using SAR=1/1
[libx264 @ 0000027bcea8bd80] frame MB size (120x68) > level limit (3600)
[libx264 @ 0000027bcea8bd80] MB rate (195644) > level limit (108000)
[libx264 @ 0000027bcea8bd80] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
[libx264 @ 0000027bcea8bd80] profile Constrained Baseline, level 3.1, 4:2:0, 8-bit
[libx264 @ 0000027bcea8bd80] 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\c94d8b28b63147139729a17a764560d5.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= 60 q=-1.0 Lsize= 136079kB time=00:05:00.13 bitrate=3714.2kbits/s speed=2.49x
video:133403kB audio:2527kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.109709%
[aac @ 0000027bcea8a400] Qavg: 1648.401
[libx264 @ 0000027bcea8bd80] frame I:240 Avg QP:15.95 size:145845
[libx264 @ 0000027bcea8bd80] frame P:6957 Avg QP:19.64 size: 14604
[libx264 @ 0000027bcea8bd80] mb I I16..4: 43.8% 0.0% 56.2%
[libx264 @ 0000027bcea8bd80] 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 @ 0000027bcea8bd80] coded y,uvDC,uvAC intra: 28.9% 51.9% 14.9% inter: 6.0% 15.3% 0.1%
[libx264 @ 0000027bcea8bd80] i16 v,h,dc,p: 47% 23% 15% 15%
[libx264 @ 0000027bcea8bd80] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 22% 22% 18% 6% 8% 5% 7% 5% 6%
[libx264 @ 0000027bcea8bd80] i8c dc,h,v,p: 61% 18% 17% 4%
[libx264 @ 0000027bcea8bd80] ref P L0: 77.2% 22.8%
[libx264 @ 0000027bcea8bd80] kb/s:3640.66
E:\360MoveData\Users\xxx\Desktop\c94d8b28b63147139729a17a764560d5.mp4Process finished with exit code 0
结果视频信息
没啥好总结的,正好用到了就分享下,大家用的时候看着改。
分享今天的心情:
这个冬天怎么还没过去,这么冷!
如果本文对你有帮助的话,点个赞吧,谢谢!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。