Java实现视频裁剪

<dependency>
      <groupId>cn.hutoolgroupId>
      <artifactId>hutool-allartifactId>
      <version>5.8.5version>
    dependency>


    <dependency>
      <groupId>org.bytedecogroupId>
      <artifactId>javacv-platformartifactId>
      <version>1.5.5version>
    dependency>

import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;

import java.util.Map;


public class Test {


    /**
     * 生成预览视频
     *
     * @param sourcePath
     * @param targetPath
     */
    public static void generatePreviewVideo(String sourcePath, String targetPath, long startMin, long durationMin) {
        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(sourcePath);
             FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(targetPath, grabber.getImageWidth(), grabber.getImageHeight(), 2)) {
            grabber.start();
            // 重新设置 宽高
            recorder.setImageWidth(grabber.getImageWidth());
            recorder.setImageHeight(grabber.getImageHeight());

            // 解决生成的视频无法播放的问题
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
            recorder.setFormat("mov");
            recorder.setFrameRate(grabber.getFrameRate());
            recorder.setSampleRate(grabber.getSampleRate());
            recorder.setAudioChannels(grabber.getAudioChannels());
            recorder.setFrameRate(grabber.getFrameRate());

            grabber.setTimestamp(startMin * 60 * 1000000);

            Map<String, Object> filter = MapUtil.filter(BeanUtil.beanToMap(grabber));

            BeanUtil.copyProperties(filter, recorder);

            recorder.start();

            Frame inFrame;
            int count = 0;
            while ((inFrame = grabber.grab()) != null) {
                // System.out.println(inFrame.timestamp);
//                if (inFrame.timestamp >= 50 * 1000 * 1000) {
//                    break;
//                }
                if (count > durationMin*60*100) {
                    break;
                }
                count++;
                recorder.record(inFrame);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String inFile = "/Users/reedfan/Desktop/监控系统.mov";   //读取的视频
        String outFile = "/Users/reedfan/Desktop/test1.mov";  //将要生成的剪切视频
        generatePreviewVideo(inFile, outFile,1,1);
//        test();
    }
}

你可能感兴趣的:(java,音视频,开发语言)