xml
<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>
java
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();
}
}