悄摸直播(一)—— 推流器的實現(獲取筆記本攝像頭畫面,轉流推流到rtmp服務器)

悄摸直播 —— JavaCV實現本機攝像頭畫面遠程直播html

推流器

1、功能說明

獲取pc端的攝像頭流數據 + 展現直播效果 + 推流到rtmp服務器

2、代碼實現

/**
	 * 推流器
	 * @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毫秒/幀
		}
	}

3、測試推流器

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窗口,並可以播放攝像頭畫面,則說明推流器成功。java

相關文章
相關標籤/搜索