当前位置:   article > 正文

Java 给视频添加背景音乐 | Java工具_java video audio encoder

java video audio encoder

目录

前言

Maven依赖

环境依赖

代码

总结


前言

本文提供给视频添加背景音乐的java工具,一如既往的实用主义。

Maven依赖

  1. <dependency>
  2. <groupId>com.google.guava</groupId>
  3. <artifactId>guava</artifactId>
  4. <version>30.1.1-jre</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.bytedeco</groupId>
  8. <artifactId>javacv-platform</artifactId>
  9. <version>1.5.5</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>cn.hutool</groupId>
  13. <artifactId>hutool-all</artifactId>
  14. <version>5.5.2</version>
  15. </dependency>

 

环境依赖

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

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

代码

不废话,上代码。下面为功能实现的主要代码。

  1. package ai.guiji.csdn.tools;
  2. import cn.hutool.core.util.IdUtil;
  3. import com.google.common.base.Joiner;
  4. import com.google.common.base.Splitter;
  5. import java.io.File;
  6. import java.text.MessageFormat;
  7. import java.util.Arrays;
  8. import java.util.List;
  9. /** @Author 剑客阿良_ALiang @Date 2023/2/20 19:31 @Description: 视频增加背景音乐 */
  10. public class AddBgmUtils {
  11. /**
  12. * 视频增加背景音乐
  13. *
  14. * @param videoPath 视频地址
  15. * @param audioPath 音频地址
  16. * @param outputDir 输出目录
  17. * @param duration 视频时长
  18. * @return 结果视频地址
  19. */
  20. public static String addBgm(
  21. String videoPath, String audioPath, String outputDir, Integer duration) throws Exception {
  22. List<String> videoPaths = Splitter.on(".").splitToList(videoPath);
  23. String videoExt = videoPaths.get(videoPaths.size() - 1);
  24. if (!Arrays.asList("mp4", "flv", "avi").contains(videoExt)) {
  25. throw new Exception("format error");
  26. }
  27. List<String> audioPaths = Splitter.on(".").splitToList(audioPath);
  28. String audioExt = audioPaths.get(audioPaths.size() - 1);
  29. if (!Arrays.asList("mp3").contains(audioExt)) {
  30. throw new Exception("format error");
  31. }
  32. String resultPath =
  33. Joiner.on(File.separator)
  34. .join(Arrays.asList(outputDir, IdUtil.simpleUUID() + "." + videoExt));
  35. ProcessBuilder builder =
  36. new ProcessBuilder(
  37. "C:\\ffpg\\bin\\ffmpeg.exe",
  38. "-i",
  39. videoPath,
  40. "-i",
  41. audioPath,
  42. "-ac",
  43. "1",
  44. "-acodec",
  45. "aac",
  46. "-ar",
  47. "48000",
  48. "-filter_complex",
  49. MessageFormat.format(
  50. "[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}",
  51. String.valueOf(duration), String.valueOf(100 * duration)),
  52. "-g",
  53. "30",
  54. "-keyint_min",
  55. "30",
  56. "-level",
  57. "3.1",
  58. "-preset:v",
  59. "medium",
  60. "-profile:v",
  61. "baseline",
  62. "-sc_threshold",
  63. "0",
  64. "-vcodec",
  65. "libx264",
  66. resultPath);
  67. builder.inheritIO().start().waitFor();
  68. return resultPath;
  69. }
  70. public static void main(String[] args) throws Exception {
  71. System.out.println(
  72. addBgm(
  73. "E:\\360MoveData\\Users\\xxx\\Desktop\\movie.mp4",
  74. "E:\\360MoveData\\Users\\xxx\\Desktop\\1.mp3",
  75. "E:\\360MoveData\\Users\\xxx\\Desktop",
  76. 300));
  77. }
  78. }

代码说明

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.mp4

Process finished with exit code 0

结果视频信息

总结

没啥好总结的,正好用到了就分享下,大家用的时候看着改。

分享今天的心情:

        这个冬天怎么还没过去,这么冷!

如果本文对你有帮助的话,点个赞吧,谢谢!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/759614
推荐阅读
相关标签
  

闽ICP备14008679号