Java 合并多个MP4视频文件

 更新时间:2020-11-19 17:00:43   作者:佚名   我要评论(0)

局限性
只支持MP4文件

经过尝试对于一些MP4文件分割不了
依赖


<!-- mp4文件操作jar -->
<!-- https://mvnrepository.com/artifact/com.googlecode.mp4parser/is

局限性

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

依赖

<!-- mp4文件操作jar -->
<!-- https://mvnrepository.com/artifact/com.googlecode.mp4parser/isoparser -->
<dependency>
<groupId>com.googlecode.mp4parser</groupId>
<artifactId>isoparser</artifactId>
<version>1.1.22</version>
</dependency>

工具类

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<String> videoList, File mergeVideoFile) {
  FileOutputStream fos = null;
  FileChannel fc = null;
  try {
   List<Movie> sourceMovies = new ArrayList<>();
   for (String video : videoList) {
    sourceMovies.add(MovieCreator.build(video));
   }

   List<Track> videoTracks = new LinkedList<>();
   List<Track> 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_h1080p/suckerpunch-distantplanet_h1080p.mov", "r").getChannel());
   Movie movie = MovieCreator.build(srcVideoPath);

   List<Track> tracks = movie.getTracks();
   movie.setTracks(new LinkedList<Track>());
   // 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];
 }

}

以上就是Java 合并多个MP4视频文件的详细内容,更多关于Java 合并视频的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
  • 使用开源项目JAVAE2 进行视频格式转换
  • java使用ffmpeg实现上传视频的转码提取视频的截图等功能(代码操作)
  • java使用ffmpeg处理视频的方法
  • 使用Java和ffmpeg把音频和视频合成视频的操作方法
  • Java解码H264格式视频流中的图片
  • JavaCV获取视频文件时长的方法
  • Java使用OpenCV3.2实现视频读取与播放
  • JavaCV实现获取视频每帧并保存
  • javacv视频抽帧的实现过程详解(附代码)
  • Java获取视频时长及截取帧截图详解
  • Java通过调用FFMPEG获取视频时长

相关文章

  • Java 合并多个MP4视频文件

    Java 合并多个MP4视频文件

    局限性 只支持MP4文件 经过尝试对于一些MP4文件分割不了 依赖 <!-- mp4文件操作jar --> <!-- https://mvnrepository.com/artifact/com.googlecode.mp4parser/is
    2020-11-19
  • SpringBoot获取Request和Response方法代码解析

    SpringBoot获取Request和Response方法代码解析

    通过静态方法获取,你也可以封装一个静态方法出来 @GetMapping(value = "") public String center() { ServletRequestAttributes servletRequestAttributes = (
    2020-11-19
  • 9个小技巧让你的Java if else看起来更优雅

    9个小技巧让你的Java if else看起来更优雅

    前言 if else 是我们写代码时,使用频率最高的关键词之一,然而有时过多的 if else 会让我们感到脑壳疼,例如下面这个伪代码: 是不是很奔溃?虽然他是伪代码,并且
    2020-11-19
  • Docker 制作镜像Dockerfile和commit操作

    Docker 制作镜像Dockerfile和commit操作

    构建镜像 构建镜像主要有两种方式: 使用docker commit命令从运行中的容器提交为镜像; 使用docker build命令从 Dockerfile 构建镜像。 首先介绍下如何从运行中的容
    2020-11-19
  • python实现文件分片上传的接口自动化

    python实现文件分片上传的接口自动化

    背景和目的: 利用python request 编写脚本测试公司系统的文件上传接口。前端读取文件的大小然后文件分片传给后端,后端将每一片数据重新组合成文件。大概的过程
    2020-11-19
  • Python爬虫如何破解JS加密的Cookie

    Python爬虫如何破解JS加密的Cookie

      通过Fiddler抓包比较,基本可以确定是JavaScript生成加密Cookie导致原来的请求返回521。 发现问题:   打开Fiddler软件,用浏览器打开目标站点(http://www.ku
    2020-11-19
  • Python并发爬虫常用实现方法解析

    Python并发爬虫常用实现方法解析

    在进行单个爬虫抓取的时候,我们不可能按照一次抓取一个url的方式进行网页抓取,这样效率低,也浪费了cpu的资源。目前python上面进行并发抓取的实现方式主要有以下几
    2020-11-19
  • Python类class参数self原理解析

    Python类class参数self原理解析

    1.self只有在类的方法中才会有,其他函数或方法是不必带self的。 2.在调用时不必传入相应的参数。 3.在类的方法中(如__init__),第一参数永远是self,表示创
    2020-11-19
  • vue-drawer-layout实现手势滑出菜单栏

    vue-drawer-layout实现手势滑出菜单栏

    本文实例为大家分享了vue-drawer-layout实现手势滑出菜单栏的具体代码,供大家参考,具体内容如下 文档链接地址 安装 npm install vue-drawer-layout --save ma
    2020-11-19
  • JavaScript实现无限轮播效果

    JavaScript实现无限轮播效果

    本文实例为大家分享了JavaScript实现无限轮播效果的具体代码,供大家参考,具体内容如下 效果展示 原理 图片说明原理 轮播顺序:1–>2–>3–>4–>5–>1的副本–>2
    2020-11-19

最新评论