对rtsp视频流存储
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class VideoRecorderService {
static SimpleDateFormat DataFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
static SimpleDateFormat TimeFormat = new java.text.SimpleDateFormat("HH-mm-ss");
private String inputFile = Constants.LBXINPUT;
private String outputFile = Constants.VIDEOOUTPUTPATH + "\\%Y-%m-%d_%H-%M-%S.mp4";
public void startRecordVideo()
throws Exception {
String url = "D:\\项目\\AIO\\recorder\\" +(new java.text.SimpleDateFormat("yyyy-MM-dd")).format(new Date()) ;
File localPath = new File(url);
if (!localPath.exists()) {
localPath.mkdirs();
}
frameRecord(inputFile, outputFile,1);
}
public void frameRecord(String inputFile, String outputFile, int audioChannel)
throws Exception, org.bytedeco.javacv.FrameRecorder.Exception {
boolean isStart=true;
FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
grabber.setOption("rtsp_transport", "tcp");
grabber.setOption("stimeout","3000000");
grabber.setImageWidth(1280);
grabber.setImageHeight(720);
grabber.setImageScalingFlags(0);
grabber.setFrameRate(25);
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 1280,720, audioChannel);
recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC);
avutil.av_log_set_level(avutil.AV_LOG_ERROR);
recorder.setOption("strftime", "1");
recorder.setFormat("segment");
recorder.setOption("segment_time", "10");
recorder.setOption("segment_filename", "10");
recorder.setOption("segment_list_flags", "live");
recorder.setOption("segment_atclocktime", "1");
recorder.setOption("reset_timestamps", "1");
recorder.setFrameRate(25);
recorder.setGopSize(50);
recorder.setVideoQuality(0.8);
recorder.setVideoBitrate(2000000);
recordByFrame(grabber, recorder, isStart);
}
private void recordByFrame(FFmpegFrameGrabber grabber, FFmpegFrameRecorder recorder, Boolean status)
throws Exception, org.bytedeco.javacv.FrameRecorder.Exception {
try {
grabber.start();
recorder.start();
Frame frame = null;
while (status&& (frame = grabber.grabFrame()) != null) {
recorder.record(frame);
}
recorder.stop();
grabber.stop();
} catch (org.bytedeco.javacv.FrameRecorder.Exception e) {
try {
e.printStackTrace();
System.out.println("录制器启动失败,正在重新启动...");
if (recorder != null) {
System.out.println("尝试关闭录制器");
recorder.stop();
grabber.stop();
System.out.println("尝试重新开启录制器");
frameRecord(inputFile,outputFile,1);
}
} catch (org.bytedeco.javacv.FrameRecorder.Exception e1) {
throw e;
}
}finally {
if (grabber != null) {
grabber.stop();
}
}
}
}