Java实现视频裁剪

发布时间:2024年01月20日
<dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
      <version>5.8.5</version>
    </dependency>


    <dependency>
      <groupId>org.bytedeco</groupId>
      <artifactId>javacv-platform</artifactId>
      <version>1.5.5</version>
    </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();
    }
}
文章来源:https://blog.csdn.net/reed1991/article/details/135717351
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。