用MP4parser合并MP4视频文件

首先 导入关联 .jar文件

compile 'com.googlecode.mp4parser:isoparser:1.1.21'
也可以使用下载jar包

关联完成之后使用下面代码就可实现合并




public class MergerMp4 {

    public  void mergeMP4(){
        List fileList = new ArrayList();
        List moviesList = new LinkedList<>();
//添加需要合并的文件
        fileList.add("/sdcard/video/20161122135659.mp4");
        fileList.add("/sdcard/video/20161122135810.mp4");
        fileList.add("/sdcard/video/20161122144321.mp4");
        fileList.add("/sdcard/video/20161122144357.mp4");
        fileList.add("/sdcard/video/20161122144447.mp4");

        try{
            for (String file : fileList)
            {
                moviesList.add(MovieCreator.build(file));
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        List videoTracks = new LinkedList();
        List audioTracks = new LinkedList();
        for (com.googlecode.mp4parser.authoring.Movie m : moviesList)
        {
            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();

        try
        {
            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()])));
            }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block  e.printStackTrace();
        }

        Container out = new DefaultMp4Builder().build(result);

        try
        {
//输出合并后的文件
            FileChannel fc = new RandomAccessFile("/sdcard/video/small/output2.mp4", "rw").getChannel();
            out.writeContainer(fc);
            fc.close();
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block  e.printStackTrace();
        }

        moviesList.clear();
        fileList.clear();

    }

}

你可能感兴趣的:(用MP4parser合并MP4视频文件)