Java 合并多个MP4视频文件
作者:泡沫幻影 发布时间:2022-08-23 12:09:19
标签: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];
}
}
来源:https://www.cnblogs.com/yxgmagic/p/11983149.html
0
投稿
猜你喜欢
- equalsIgnoreCase() 方法用于将字符串与指定的对象比较,不考虑大小写。实例equals() 会判断大小写区别,equalsI
- 作为一个ORM框架,hibernate肯定也需要满足我们实现表与表之间进行关联的需要。hibernate在关联方法的实现很简单。下面我们先来
- 1、通过C#调用Java的方法:在C#中添加调用的一些代码,利用Unity提供的一些接口实现调用Java!private const str
- 1.理解全过程1.1.概述需要具备的知识Socket网络编程反向代理的理解平滑加权轮询算法的理解线程池的理解目的:实现Socket 集群服务
- 一、背景Apache POI 是创建和维护操作各种符合Office Open XML(OOXML)标准和微软的OLE 2复合文档格式(OLE
- WHY朋友在群里求助一个问题,问题原型是这样的:String str = "{{10.14, 11.24, 44.55, 41.0
- 一、概述UDP和TCP是网络通讯常用的两个传输协议,C#一般可以通过Socket来实现UDP和TCP通讯,由于.NET框架通过UdpClie
- 1.application.ymlserver: port: 8184spring: application: &n
- 一、同步调用1、同步调用会按照代码顺序来执行2、同步调用会阻塞线程,如果是要调用一项繁重的工作(如大量IO操作),可能会让程序停顿很长时间,
- 一、前言学习概述:学习四种不同类型的方法应用、方法被调用时的内存图、重载学习目标:熟练掌握方法的应用以及重载二、定义与调用1.概述定义:方法
- public class TimeUtil { public static final int SECO
- 为了让大家知道下面内容是否是自己想要的,我先发效果图。好了,那就开始贴代码了以下为一个按钮的事件,为裁剪准备图片、裁剪路径、保存路径priv
- 递归方法定义本身调用方法本身的现象叫做递归在这之前我们学的东西:例如StringBuffer.append().append().appen
- 讲这个例子前,咱们先来看一个简单的程序:字符串数组实现数字转字母:#include <stdio.h>#include <
- 多线程内容大致分两部分,其一是异步操作,可通过专用,线程池,Task,Parallel,PLINQ等,而这里又涉及工作线程与IO线程;其二是
- 提到java里的注解,和我们平时的注释还是有很大的区别,主要是作为java特性来使用的,跟我们常见的类是同一个使用的层面。关于java注解的
- 这是一次阿里面试里被问到的题目,在我的印象中,final修饰的方法是不能被子类重写的。如果在子类中重写final修饰的方法,在编译阶段就会提
- 定义注解也叫原数据,它是JDK1.5及之后版本引入的一个特性,它可以声明在类、方法、变量等前面,用来对这些元素进行说明。作用生成文档:通过代
- 前言《JAVA打砖块》游戏是自制的游戏。玩家操作一根萤幕上水平的“棒子”,让一颗不断弹来弹去的&am
- 资源加载器使用Java,您可以使用当前线程的classLoader并尝试加载文件,但是Spring Framework为您提供了更为优雅的解