카테고리 없음

WebRTC를 이용한 스크린 캡처 스트림 영상 만들기

Wood Pecker 2022. 3. 17. 11:35

1. 개요.

웹브라우저의 자바스크립트에서 WebRTC를 이용한 현재 PC화면을 스크린 캡처하여 스트림 영상으로 만들고 이를 디스플레이 하여 본다. 이 스트림을 원격 컴퓨터에 보내면 화면 공유 기능이 된다. 화면 공유를 위한 사전 단계이다.

 

2. 프로그램
node.js 환경에서 테스트 하였지만 아파치 서버에서도 별 문제는 없을 것이다. 다음과 같은 html 파일을 만들고 https 로 불러 보자. 크롬과 FireFox 에서 테스트 하는 것이 안정적으로 동작한다.

<!DOCTYPE html>
<html>
<head>
  <title>Screen Streaming</title>
  <link rel="stylesheet" href="/css/main.css" />
</head>

<body>

  <h1>Realtime communication with WebRTC</h1>

  <p>This example shows you the contents of the selected part of your display.
     Click the Start Capture button to begin.</p>
 
   <p>
      <button id="start">Start Capture</button>&nbsp;<button id="stop">Stop Capture</button></p>
      <video id="screen_video" autoplay></video><br>
      <strong>Log:</strong><br>
      <pre id="log"></pre>
      <script src="/socket.io/socket.io.js"></script>
      <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
  
  <script>
	const videoElem = document.getElementById("screen_video");
    const logElem = document.getElementById("log");
    const startElem = document.getElementById("start");
    const stopElem = document.getElementById("stop");
   
    var displayMediaOptions = {
       video: {
          cursor: "always"
        },
	    audio: false
     };
     function startCapture() {
         logElem.innerHTML = "";
         try {
			  navigator.mediaDevices.getDisplayMedia(displayMediaOptions)
				 .then((stream) => {
                    videoElem.srcObject = stream
                    videoElem.onloadedmetadata = () => {
                           videoElem.play()
                    }
				});
        } catch(err) {
             console.error("Error: " + err);
        }
     }

	 function stopCapture(evt) {
       let tracks = videoElem.srcObject.getTracks();
       tracks.forEach(track => track.stop());
	   dumpOptionsInfo();
       videoElem.srcObject = null;
     }

     function dumpOptionsInfo() {
	    if(videoElem.srcObject){
			const videoTrack = videoElem.srcObject.getVideoTracks()[0];
			console.info("Track settings:");
			console.info(JSON.stringify(videoTrack.getSettings(), null, 2));
			console.info("Track constraints:");
			console.info(JSON.stringify(videoTrack.getConstraints(), null, 2));
		}
     }

    startElem.addEventListener("click", function(evt) { startCapture(); }, false);
    stopElem.addEventListener("click", function(evt)  { stopCapture();  }, false);
  </script>
</body>

</html>

반응형