VideoUtil.java 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package com.fdkankan.fusion.common.util;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.io.*;
  4. import java.util.*;
  5. @Slf4j
  6. public class VideoUtil {
  7. public static String mergeVideo(LinkedHashSet<String> fromVideoFileList, String newVideoFile) {
  8. File tagFile = new File(newVideoFile);
  9. if(!tagFile.exists()){
  10. tagFile.mkdirs();
  11. }
  12. String fame = UUID.randomUUID().toString().replace("-","");
  13. String fileName = fame+".mp4";
  14. String imgName = fame+".jpg";
  15. try {
  16. List<String> voidTS = new ArrayList<>();
  17. for (String fromVideoFile : fromVideoFileList) {
  18. String format = "%s -y -i %s -vcodec copy -bsf:v h264_mp4toannexb -f mpegts %s";
  19. String name = UUID.randomUUID().toString().replace("-","");
  20. String command = String.format(format, "ffmpeg", fromVideoFile, newVideoFile +"/"+name + ".ts");
  21. ShellUtil.execCmd(command);
  22. voidTS.add(newVideoFile +"/"+name + ".ts");
  23. }
  24. StringBuilder tsPath = new StringBuilder();
  25. tsPath.append("ffmpeg");
  26. tsPath.append(" -i ");
  27. tsPath.append("concat:");
  28. for (int t = 0; t < voidTS.size(); t++) {
  29. if (t != voidTS.size() - 1) {
  30. tsPath.append(voidTS.get(t) + "|");
  31. } else {
  32. tsPath.append(voidTS.get(t));
  33. }
  34. }
  35. tsPath.append(" -vcodec ");
  36. tsPath.append(" copy ");
  37. tsPath.append(" -bsf:a ");
  38. tsPath.append(" aac_adtstoasc ");
  39. tsPath.append(" -movflags ");
  40. tsPath.append(" +faststart ");
  41. tsPath.append(newVideoFile).append("/").append(fileName);
  42. ShellUtil.execCmd(tsPath.toString());
  43. ffmpegVideo(newVideoFile +"/"+ fileName,newVideoFile +"/"+ imgName,"200","200");
  44. //删除生成的ts文件
  45. for (String filePath : voidTS) {
  46. File file = new File(filePath);
  47. file.delete();
  48. }
  49. return fileName;
  50. } catch (Exception e) {
  51. e.printStackTrace();
  52. log.error(" 合并失败-{}", e.getMessage());
  53. return null;
  54. }
  55. }
  56. /**
  57. *
  58. * @param sourceFile 原文件路径
  59. * @param thumbFile 目标文件路径
  60. * @param thumbWidth 宽度
  61. * @param thumbHigh 高度
  62. * @return
  63. * ffmpeg -i bb.mp4 -y -vframes 1 -vf scale=100:100/a thumb.jpg
  64. */
  65. public static boolean ffmpegVideo(String sourceFile, String thumbFile, String thumbWidth, String thumbHigh){
  66. String cmd = " ffmpeg -i " + sourceFile + " -y -vframes 1 -vf scale=" + thumbWidth + ":" + thumbHigh + "/a " + thumbFile;
  67. ShellUtil.execCmd(cmd);
  68. File file = new File(thumbFile);
  69. if(!file.exists()){
  70. return false;
  71. }
  72. return true;
  73. }
  74. }