Java 合并多个MP4视频文件

局限性

只支持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 合并视频的资料请关注我们其它相关文章!

(0)

相关推荐

  • 使用Java和ffmpeg把音频和视频合成视频的操作方法

    FFmpeg是一个开源免费跨平台的视频和音频流方案,属于自由软件,采用LGPL或GPL许可证(依据你选择的组件).它提供了录制.转换以及流化音视频的完整解决方案.它包含了非常先进的音频/视频编解码库libavcodec,为了保证高可移植性和编解码质量,libavcodec里很多codec都是从头开发的. FFmpeg是一套可以用来记录.转换数字音频.视频,并能将其转化为流的开源计算机程序.它包括了目前领先的音/视频编码库libavcodec. FFmpeg是在Linux下开发出来的,但它可以在包

  • javacv视频抽帧的实现过程详解(附代码)

    视频抽帧可以做一些处理,比如水印,去水印等操作,然后再合成视频.下面直接上代码: 引入maven步骤看javacv去水印的文章 这里直接上关键操作: /** * 视频文件指定时间段的帧截取 * @param file * @param start * @param end */ public static List<File> videoIntercept(File file, Integer start, Integer end) { Frame frame = null; List<

  • 使用开源项目JAVAE2 进行视频格式转换

    使用开源项目JAVAE 进行视频格式转换 JAVAE简介: JAVE (Java音频视频编码器)库是ffmpeg项目的Java包装器.开发人员可以利用JAVE2将音频和视频文件从一种格式转换为另一种格式.在示例可以转换成一个AVI文件MG,您可以更改一个DivX视频(youtube) Flash FLV,您可以转换WAV音频文件到MP3和Ogg Vorbis,您可以分离和转换音频和视频跟踪代码,您可以调整视频,改变他们的大小和比例等.JAVE2还支持许多其他格式.容器和操作. 官网地址:http

  • java使用ffmpeg实现上传视频的转码提取视频的截图等功能(代码操作)

    ffmpeg视频采集功能非常强大,不仅可以采集视频采集卡或USB摄像头的图像,还可以进行屏幕录制,同时还支持以RTP方式将视频流传送给支持RTSP的流媒体服务器,支持直播应用.ffmpeg能解析的格式和不能解析的格式都一一给大家说明了,具体内容详情跟随一起看看吧, 1.能支持的格式 ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等) 2.不能支持的格式 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),可以先用别的工具(menco

  • JavaCV获取视频文件时长的方法

    本文实例为大家分享了JavaCV获取视频文件时长的具体代码,供大家参考,具体内容如下 1.做项目时,需要读取视频文件的时长,网上有很多通过自己写的JNI接口来实现,但由于项目使用了JavaCV和OpenCV,其中有一些处理视频的接口,所以还是想打算尽可能使用JavaCV和OpenCV来实现,经过查阅了相关的一些资料,实现了使用JavaCV获取视频文件时长的功能. 2.基本实现思路:获取视频的总帧数和每秒帧数(FPS),然后通过公式:视频总帧数/每秒帧数(FPS)=时长(单位秒) 3.实现代码如下

  • Java通过调用FFMPEG获取视频时长

    FFmpeg是一套可以用来记录.转换数字音频.视频,并能将其转化为流的开源计算机程序.采用LGPL或GPL许可证.它提供了录制.转换以及流化音视频的完整解决方案.它包含了非常先进的音频/视频编解码库libavcodec,为了保证高可移植性和编解码质量,libavcodec里很多codec都是从头开发的. 由此看来FFmpeg很强大,很多主流的音频.视频处理软件都使用了FFmpeg. FFmpeg下载下来解压,cmd进入到FFmpeg.exe目录中,即可在命令行下进行各种操作,查看视频信息命令:f

  • Java获取视频时长及截取帧截图详解

    前言 只是最近碰到有这方面的项目需求,所以简单 Mark 下本文.下面的示例是参考过他人分享的文章,之后本人再自行实践.调整和测试过的,希望对有这方面需求的人有所帮助. 示例 添加依赖 <dependency> <groupId>org.bytedeco</groupId> <artifactId>javacv-platform</artifactId> <version>1.4.4</version> </depe

  • java使用ffmpeg处理视频的方法

    FFmpeg是一套可以用来记录.转换数字音频.视频,并能将其转化为流的开源计算机程序.采用LGPL或GPL许可证.它提供了录制.转换以及流化音视频的完整解决方案. 官网链接http://ffmpeg.org/ 1.下载并解压windows版本安装包 2.windows本地使用命令行测试 1.修改格式测试(转码) 将需要修改的视频A.avi 提前放在bin目录下 在bin目录下cmd进入命令行 输入命令完成转码成B.mp4 ffmpeg.exe -i A.avi -y B.mp4 2.视频音频结合

  • JavaCV实现获取视频每帧并保存

    兴趣使然写的代码,因为没有接触过JavaCV,所以查了很久的API还有依赖包,也使用了openCV来写过,但是还是遇到很多问题.希望小伙伴指出不足,互相学习. 环境配置: JavaCV1.4.1(下载Jar包,解压并提取所需要的Jar.这点耗时比较长,萌新完全不知道需要用什么,看源码及例子推出) Java版本:Java10 具体代码: package VideoProcessing; import org.bytedeco.javacv.FFmpegFrameGrabber; import or

  • Java使用OpenCV3.2实现视频读取与播放

    Java使用OpenCV3.2实现视频读取与播放,供大家参考,具体内容如下 OpenCV从3.x版本开始其JAVA语言的SDK支持视频文件读写,这样就极大的方便了广大Java语言开发者学习与使用OpenCV,通过摄像头或者视频文件读取帧的内容与播放,完成视频内容分析与对象跟踪等各种应用开发任务.可以说OpenCV C++ SDK可以做到绝大多数事情,在OpenCV3.x版本上用Java都可以完成,这样就为很多Java开发者学习OpenCV打开了方便之门. 实现思路 首先用OpenCV相关API读

  • Java解码H264格式视频流中的图片

    本文实例为大家分享了Java解码H264格式视频流中的图片,供大家参考,具体内容如下 引入依赖 <dependency> <groupId>org.bytedeco</groupId> <artifactId>javacv</artifactId> <version>1.4.3</version> </dependency> <dependency> <groupId>org.byted

随机推荐