VideoUtil.java 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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,Boolean newCover) {
  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 h264 -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. if(newCover){
  44. ffmpegVideo(newVideoFile +"/"+ fileName,newVideoFile +"/"+ imgName,"200","200");
  45. }
  46. //删除生成的ts文件
  47. for (String filePath : voidTS) {
  48. File file = new File(filePath);
  49. //file.delete();
  50. }
  51. return fileName;
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. log.error(" 合并失败-{}", e.getMessage());
  55. return null;
  56. }
  57. }
  58. /**
  59. *
  60. * @param sourceFile 原文件路径
  61. * @param thumbFile 目标文件路径
  62. * @param thumbWidth 宽度
  63. * @param thumbHigh 高度
  64. * @return
  65. * ffmpeg -i bb.mp4 -y -vframes 1 -vf scale=100:100/a thumb.jpg
  66. */
  67. public static boolean ffmpegVideo(String sourceFile, String thumbFile, String thumbWidth, String thumbHigh){
  68. String cmd = " ffmpeg -i " + sourceFile + " -y -vframes 1 -vf scale=" + thumbWidth + ":" + thumbHigh + "/a " + thumbFile;
  69. ShellUtil.execCmd(cmd);
  70. File file = new File(thumbFile);
  71. if(!file.exists()){
  72. return false;
  73. }
  74. return true;
  75. }
  76. }