在好例子网,分享、交流、成长!
您当前所在位置:首页Java 开发实例Android平台开发 → java 合并mp4视频文件(亲测可用)

java 合并mp4视频文件(亲测可用)

Android平台开发

下载此实例
  • 开发语言:Java
  • 实例大小:9.38M
  • 下载次数:39
  • 浏览次数:2374
  • 发布时间:2016-07-22
  • 实例类别:Android平台开发
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 视频 文件 mp4 java

实例介绍

【实例简介】

【实例截图】

下图是合并后的结果

from clipboard

【核心代码】


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import com.coremedia.iso.IsoFile;
import com.coremedia.iso.boxes.Container;
import com.coremedia.iso.boxes.TimeToSampleBox;
import com.googlecode.mp4parser.DataSource;
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;


/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Modified example based on mp4parser google code open source project.
// http://code.google.com/p/mp4parser/source/browse/trunk/examples/src/main/java/com/googlecode/mp4parser/ShortenExample.java


/**
 * Shortens/Crops a track
 */
public class ShortenExample {

	public static void main(String args[]){
		try {
			//startTrim(new File("D:\\Mp4\\Wonders_of_Nature.mp4"),new File("D:\\Mp4\\new.mp4"),17000,35000);
			//startTrim(new File("D:\\Mp4\\test.mp4"),new File("D:\\Mp4\\test1.mp4"),3000,7000);
			//appendVideo(new String[]{"D:\\Mp4\\begin.mp4","D:\\Mp4\\end.mp4","D:\\Mp4\\append1.mp4"});
			appendVideo(new String[]{"D:\\Mp4\\test.mp4","D:\\Mp4\\test1.mp4"});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void startTrim(File src, File dst, int startMs, int endMs) throws IOException {
        
		//ReadableByteChannel in = Channels.newChannel((new FileInputStream(src)));
        Movie movie = MovieCreator.build("D:\\Mp4\\test.mp4");
		//RandomAccessFile randomAccessFile = new RandomAccessFile(src, "r");
		
		//DataSource ds = DataSource.
        //Movie movie = MovieCreator.build("D:\\Mp4\\test.mp4");//randomAccessFile.getChannel()

        // remove all tracks we will create new tracks from the old
        List<Track> tracks = movie.getTracks();
        movie.setTracks(new LinkedList<Track>());
        for (Track track : tracks) {
        	printTime(track);
        }
        
        double startTime = startMs/1000;
        double endTime = endMs/1000;

        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.");
                }
                startTime = correctTimeToSyncSample(track, startTime, false);//true
                endTime = correctTimeToSyncSample(track, endTime, true);//false
                timeCorrected = true;
            }
        }
        System.out.println("trim startTime-->" startTime);
        System.out.println("trim endTime-->" endTime);
        int x = 0;
        for (Track track : tracks) {
            long currentSample = 0;
            double currentTime = 0;
            long startSample = -1;
            long endSample = -1;
            x  ;
            for (int i = 0; i < track.getDecodingTimeEntries().size(); i  ) {
                TimeToSampleBox.Entry entry = track.getDecodingTimeEntries().get(i);
                for (int j = 0; j < entry.getCount(); j  ) {
                    // entry.getDelta() is the amount of time the current sample covers.

                    if (currentTime <= startTime) {
                        // current sample is still before the new starttime
                        startSample = currentSample;
                    }
                    if (currentTime <= endTime) {
                        // current sample is after the new start time and still before the new endtime
                        endSample = currentSample;
                    } else {
                        // current sample is after the end of the cropped video
                        break;
                    }
                    currentTime  = (double) entry.getDelta() / (double) track.getTrackMetaData().getTimescale();
                    currentSample  ;
                }
            }
            
            System.out.println("trim startSample-->" startSample);
            System.out.println("trim endSample-->" endSample);
            movie.addTrack(new CroppedTrack(track, startSample, endSample));
            break;
        }
        //movie.addTrack(new CroppedTrack(track, startSample, endSample));
        
        //IsoFile out = (IsoFile) new DefaultMp4Builder().build(movie);
        Container container = new DefaultMp4Builder().build(movie);
        
        if (!dst.exists()) {
            dst.createNewFile();
        }
 
        FileOutputStream fos = new FileOutputStream(dst);
        FileChannel fc = fos.getChannel();
        //out.getBox(fc);  // This one build up the memory.
        container.writeContainer(fc);
        
        fc.close();
        fos.close();
        //randomAccessFile.close();
    }
	public void startAppend(){
		
	}
	public static void appendVideo(String[] videos) throws IOException{
        Movie[] inMovies = new Movie[videos.length];
        int index = 0;
        for(String video:videos)
        {
			inMovies[index] = MovieCreator.build(video);
        	index  ;
    	}
        List<Track> videoTracks = new LinkedList<Track>();
        List<Track> audioTracks = new LinkedList<Track>();
        for (Movie m : inMovies) {
            for (Track t : m.getTracks()) {
                if (t.getHandler().equals("soun")) {
                    audioTracks.add(t);
                }
                if (t.getHandler().equals("vide")) {
                    videoTracks.add(t);
                }
            }
        }

        Movie result = new Movie();

        if (audioTracks.size() > 0) {
			result.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
        }
        if (videoTracks.size() > 0) {
			result.addTrack(new AppendTrack(videoTracks.toArray(new Track[videoTracks.size()])));
        }
        Container out = new DefaultMp4Builder().build(result);
        FileChannel fc = new RandomAccessFile(String.format("D:\\Mp4\\append2.mp4"), "rw").getChannel();
        out.writeContainer(fc);
        fc.close();
    }
	
    protected static long getDuration(Track track) {
        long duration = 0;
        for (TimeToSampleBox.Entry entry : track.getDecodingTimeEntries()) {
            duration  = entry.getCount() * entry.getDelta();
        }
        return duration;
    }

    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.getDecodingTimeEntries().size(); i  ) {
            TimeToSampleBox.Entry entry = track.getDecodingTimeEntries().get(i);
            for (int j = 0; j < entry.getCount(); j  ) {
                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) entry.getDelta() / (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];
    }
    
    private static void printTime(Track track) {
        double[] timeOfSyncSamples = new double[track.getSyncSamples().length];
        long currentSample = 0;
        double currentTime = 0;
        for (int i = 0; i < track.getDecodingTimeEntries().size(); i  ) {
            TimeToSampleBox.Entry entry = track.getDecodingTimeEntries().get(i);
            for (int j = 0; j < entry.getCount(); j  ) {
                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;
                    System.out.println("currentTime-->" currentTime);
                }
                currentTime  = (double) entry.getDelta() / (double) track.getTrackMetaData().getTimescale();
                currentSample  ;
            }
        }
        
        //System.out.println("size-->" currentSample);
        /*for(int i=0;i<timeOfSyncSamples.length;i  ){
        	System.out.println("data-->" timeOfSyncSamples[i]);
        }*/
        
        /*double previous = 0;
        for (double timeOfSyncSample : timeOfSyncSamples) {
            if (timeOfSyncSample > cutHere) {
                if (next) {
                    return timeOfSyncSample;
                } else {
                    return previous;
                }
            }
            previous = timeOfSyncSample;
        }
        return timeOfSyncSamples[timeOfSyncSamples.length - 1];*/
    }

}



标签: 视频 文件 mp4 java

实例下载地址

java 合并mp4视频文件(亲测可用)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警