使用Java怎么样实现一个合并MP4视频功能
创始人
2024-11-20 02:01:51
0次

局限性

只支持MP4文件
经过尝试对于一些MP4文件分割不了

依赖




com.googlecode.mp4parser
isoparser
1.1.22

工具类

package com.example.demo;


import com.coremedia.iso.boxes.Container;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.googlecode.mp4parser.authoring.tracks.AppendTrack;
import com.googlecode.mp4parser.authoring.tracks.CroppedTrack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Mp4ParserUtils {
 /**
  * 合并视频
  *
  * @param videoList: 所有视频地址集合
  * @param mergeVideoFile: 目标文件
  * @return
  */
 public static String mergeVideo(List videoList, File mergeVideoFile) {
  FileOutputStream fos = null;
  FileChannel fc = null;
  try {
   List sourceMovies = new ArrayList<>();
   for (String video : videoList) {
    sourceMovies.add(MovieCreator.build(video));
   }

   List videoTracks = new LinkedList<>();
   List audioTracks = new LinkedList<>();

   for (Movie movie : sourceMovies) {
    for (Track track : movie.getTracks()) {
     if ("soun".equals(track.getHandler())) {
      audioTracks.add(track);
     }

     if ("vide".equals(track.getHandler())) {
      videoTracks.add(track);
     }
    }
   }

   Movie mergeMovie = new Movie();
   if (audioTracks.size() > 0) {
    mergeMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
   }

   if (videoTracks.size() > 0) {
    mergeMovie.addTrack(new AppendTrack(videoTracks.toArray(new Track[videoTracks.size()])));
   }

   Container out = new DefaultMp4Builder().build(mergeMovie);
   fos = new FileOutputStream(mergeVideoFile);
   fc = fos.getChannel();
   out.writeContainer(fc);
   fc.close();
   fos.close();
   return mergeVideoFile.getAbsolutePath();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (fc != null) {
    try {
     fc.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }

   if (fos != null) {
    try {
     fos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }

  return null;
 }

 /**
  * 剪切视频
  * @param srcVideoPath
  * @param dstVideoPath
  * @param times
  * @throws IOException
  */
 public static void cutVideo(String srcVideoPath, String dstVideoPath, double[] times) throws IOException {
  int dstVideoNumber = times.length / 2;
  String[] dstVideoPathes = new String[dstVideoNumber];
  for (int i = 0; i < dstVideoNumber; i++) {
   dstVideoPathes[i] = dstVideoPath + "cutOutput-" + i + ".mp4";
  }
  int timesCount = 0;

  for (int idst = 0; idst < dstVideoPathes.length; idst++) {
   //Movie movie = new MovieCreator().build(new RandomAccessFile("/home/sannies/suckerpunch-distantplanet_h2080p/suckerpunch-distantplanet_h2080p.mov", "r").getChannel());
   Movie movie = MovieCreator.build(srcVideoPath);

   List tracks = movie.getTracks();
   movie.setTracks(new LinkedList());
   // remove all tracks we will create new tracks from the old


   double startTime1 = times[timesCount];
   double endTime1 = times[timesCount + 1];
   timesCount = timesCount + 2;

   boolean timeCorrected = false;

   // Here we try to find a track that has sync samples. Since we can only start decoding
   // at such a sample we SHOULD make sure that the start of the new fragment is exactly
   // such a frame
   for (Track track : tracks) {
    if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) {
     if (timeCorrected) {
      // This exception here could be a false positive in case we have multiple tracks
      // with sync samples at exactly the same positions. E.g. a single movie containing
      // multiple qualities of the same video (Microsoft Smooth Streaming file)

      throw new RuntimeException("The startTime has already been corrected by another track with SyncSample. Not Supported.");
     }
     startTime1 = correctTimeToSyncSample(track, startTime1, false);
     endTime1 = correctTimeToSyncSample(track, endTime1, true);

     timeCorrected = true;
    }
   }

   for (Track track : tracks) {
    long currentSample = 0;
    double currentTime = 0;
    double lastTime = -1;
    long startSample1 = -1;
    long endSample1 = -1;


    for (int i = 0; i < track.getSampleDurations().length; i++) {
     long delta = track.getSampleDurations()[i];


     if (currentTime > lastTime && currentTime <= startTime1) {
      // current sample is still before the new starttime
      startSample1 = currentSample;
     }
     if (currentTime > lastTime && currentTime <= endTime1) {
      // current sample is after the new start time and still before the new endtime
      endSample1 = currentSample;
     }

     lastTime = currentTime;
     currentTime += (double) delta / (double) track.getTrackMetaData().getTimescale();
     currentSample++;
    }
    //movie.addTrack(new AppendTrack(new ClippedTrack(track, startSample1, endSample1), new ClippedTrack(track, startSample2, endSample2)));
    movie.addTrack(new CroppedTrack(track, startSample1, endSample1));
   }
   long start1 = System.currentTimeMillis();
   Container out = new DefaultMp4Builder().build(movie);
   long start2 = System.currentTimeMillis();
   FileOutputStream fos = new FileOutputStream(String.format(dstVideoPathes[idst]));
   FileChannel fc = fos.getChannel();
   out.writeContainer(fc);

   fc.close();
   fos.close();
   long start3 = System.currentTimeMillis();

  }
 }

 private static double correctTimeToSyncSample(Track track, double cutHere, boolean next) {
  double[] timeOfSyncSamples = new double[track.getSyncSamples().length];
  long currentSample = 0;
  double currentTime = 0;
  for (int i = 0; i < track.getSampleDurations().length; i++) {
   long delta = track.getSampleDurations()[i];

   if (Arrays.binarySearch(track.getSyncSamples(), currentSample + 1) >= 0) {
    // samples always start with 1 but we start with zero therefore +1
    timeOfSyncSamples[Arrays.binarySearch(track.getSyncSamples(), currentSample + 1)] = currentTime;
   }
   currentTime += (double) delta / (double) track.getTrackMetaData().getTimescale();
   currentSample++;

  }
  double previous = 0;
  for (double timeOfSyncSample : timeOfSyncSamples) {
   if (timeOfSyncSample > cutHere) {
    if (next) {
     return timeOfSyncSample;
    } else {
     return previous;
    }
   }
   previous = timeOfSyncSample;
  }
  return timeOfSyncSamples[timeOfSyncSamples.length - 1];
 }

}

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...