视频上传时的分块与合并处理(断点续传)

@TOC

1. 视频分块:

1.1 代码

    @Test
    public void testChunk() throws IOException {

        File source = new File("D:\\r'j'j\\video\\mmexport1644814789468.mp4");
        File chunk = new File("D:\\r'j'j\\video\\chunk\\");

        //每块大小
        long chunkSize = 1024 * 1024 * 5;
        //分块数量(向上取整)
        long chunkNum = (long) Math.ceil(source.length() * 1.0 / chunkSize);
        //设置缓存区
        byte[] bytes = new byte[1024];
        //设置流
        RandomAccessFile raf_read = new RandomAccessFile(source,"r");
        //分块
        for (long i = 0; i < chunkNum; i++) {
            //创建分块文件
            File chunkFile = new File("D:\\r'j'j\\video\\chunk\\"+i);
            if (chunkFile.exists()) chunkFile.delete();

            RandomAccessFile raf_write = new RandomAccessFile(chunkFile,"rw");
            int len = -1;
            while ((len= raf_read.read(bytes))!=-1){
                raf_write.write(bytes,0,len);
                if (chunkFile.length()>=chunkSize) break;
            }
            raf_write.close();
            System.out.println("完成分块"+i);
        }
        raf_read.close();
    }

1.2 结果

视频上传时的分块与合并处理(断点续传)_第1张图片

2. 视频合并:

2.1 代码

@Test
    public void testMerge() throws IOException {
        File source = new File("D:\\r'j'j\\video\\mmexport1644814789468.mp4");
        File chunk = new File("D:\\r'j'j\\video\\chunk\\");
        File mergeFile = new File("D:\\r'j'j\\video\\merge.mp4");
        mergeFile.createNewFile();

        //取出所有分块文件
        File[] files = chunk.listFiles();

        List<File> fileList = Arrays.asList(files);
        //排序
        Collections.sort(fileList, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                return Integer.parseInt(o1.getName())-Integer.parseInt(o2.getName());
            }
        });

        byte[] bytes = new byte[1024];
        RandomAccessFile raf_write = new RandomAccessFile(mergeFile,"rw");
        //合并
        for (File file : fileList) {
            RandomAccessFile raf_read = new RandomAccessFile(file,"r");
            int len = -1;
            while ((len= raf_read.read(bytes))!=-1){
                raf_write.write(bytes,0,len);
            }
            raf_read.close();
        }
        raf_write.close();
        //MD5检测是否与源文件一致
        try{
            FileInputStream sourceInputStream = new FileInputStream(source);
            FileInputStream mergeInputStream = new FileInputStream(mergeFile);
            String a= DigestUtils.md5Hex(sourceInputStream);
            String b= DigestUtils.md5Hex(mergeInputStream);
            if (a.equals(b)) System.out.println("合并成功!");
        }catch (Exception e){

        }
    }

2.2 结果

视频上传时的分块与合并处理(断点续传)_第2张图片

你可能感兴趣的:(音视频,java)