推流器
一、功能說明
獲取pc端的攝像頭流數據 + 展示直播效果 + 推流到rtmp服務器
二、代碼實現
/**
* 推流器
* @param devicePath 攝像頭的地址。可以是攝像頭rtsp地址,也可以是設備號碼,本機攝像頭是0
* @param outputPath 接收路徑
* @param v_rs 幀率
* @throws Exception
* @throws org.bytedeco.javacv.FrameRecorder.Exception
* @throws InterruptedException
*/
public static void recordPush(String outputPath,int v_rs) throws Exception, org.bytedeco.javacv.FrameRecorder.Exception, InterruptedException {
Loader.load(opencv_objdetect.class);
//創建采集器
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0); //本地攝像頭默認為0
//開啟采集器
try {
grabber.start();
} catch (Exception e) {
try {
grabber.restart(); //一次重啟嘗試
} catch (Exception e2) {
throw e;
}
}
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage(); //轉換器
Frame grabframe = grabber.grab(); //獲取一幀
IplImage grabbedImage = null;
if (grabframe!=null) {
grabbedImage = converter.convert(grabframe); //將這一幀轉換為IplImage
}
//創建錄制器
FrameRecorder recorder;
recorder = FrameRecorder.createDefault(outputPath, 1280, 720); //輸出路徑,畫面高,畫面寬
recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); //設置編碼格式
recorder.setFormat("flv");
recorder.setFrameRate(v_rs);
recorder.setGopSize(v_rs);
//開啟錄制器
try {
recorder.start();
} catch (java.lang.Exception e) {
System.out.println("recorder開啟失敗");
System.out.println(recorder);
try {
if (recorder != null) { //嘗試重啟錄制器
recorder.stop();
recorder.start();
}
} catch (java.lang.Exception e1) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//直播效果展示窗口
CanvasFrame frame = new CanvasFrame("直播效果",CanvasFrame.getDefaultGamma() / grabber.getGamma());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setAlwaysOnTop(true);
//推流
while(frame.isVisible() && (grabframe=grabber.grab()) != null) {
frame.showImage(grabframe); //展示直播效果
grabbedImage = converter.convert(grabframe);
Frame rotatedFrame = converter.convert(grabbedImage);
if (rotatedFrame != null) {
recorder.record(rotatedFrame);
}
Thread.sleep(50); //50毫秒/幀
}
}
三、測試推流器
public static void main(String[] args) throws Exception, org.bytedeco.javacv.FrameRecorder.Exception, InterruptedException {
//設置rtmp服務器地址
String outputPath = "rtmp://192.168.1.48:1935/live/stream";
recordPush(outputPath, 25);
}
如果出現“直播效果”的swing窗口,並能夠播放攝像頭畫面,則說明推流器成功。