본문 바로가기
JavaScript

[JavaScript] 내 화면 녹화 및 다운로드하기

by teamnova 2023. 5. 4.
728x90

 

 오늘은 내 화면을 녹화하고 다운로드 하는 예제를 가져왔습니다!

 

navigator.mediaDevices.getDisplayMedia()로 내 화면과 연결된 MediaStream을 가져오고,

MediaRecorder의 start(), stop(), ondataavailable event, stop event 를 사용해서 내 화면을 녹화하고

window.URL.createObjectURL() 로 녹화 데이터를 나타내는 url 생성한 뒤 

a element 로 해당 url 이 나타내는 데이터를 다운로드 합니다.

 

먼저 실행 결과입니다.

 

 

 

전체 코드입니다.

 

record.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <div id="container">
 
        <div>
            <button id="start">Start Sharing</button>
            <button id="record" >Start 기록</button>
            <button id="download" >Stop Recording and Download</button>
        </div>
    
    </div>
    
    <!-- include adapter for srcObject shim -->
    <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
    <script src="./record.js"></script>
    

    </body>
</html>

 

record.js

'use strict';

/* globals MediaRecorder */

let mediaRecorder;
let recordedBlobs;

const recordButton = document.querySelector('button#record');

recordButton.addEventListener('click', () => {
    startRecording();
});

const downloadButton = document.querySelector('button#download');
downloadButton.addEventListener('click', () => {
  
  stopRecording();
  

});

function handleDataAvailable(event) {
  console.log('handleDataAvailable', event);
  if (event.data && event.data.size > 0) {
    recordedBlobs.push(event.data);
  }
}

function getSupportedMimeTypes() {
  const possibleTypes = [
    'video/webm;codecs=vp9,opus',
    'video/webm;codecs=vp8,opus',
    'video/webm;codecs=h264,opus',
    'video/mp4;codecs=h264,aac',
  ];
  return possibleTypes.filter(mimeType => {
    return MediaRecorder.isTypeSupported(mimeType);
  });
}

function startRecording() {
  recordedBlobs = [];
  const mimeType = getSupportedMimeTypes()[0];
  const options = {mimeType};

  try {
    mediaRecorder = new MediaRecorder(window.stream, options);
  } catch (e) {
    console.error('Exception while creating MediaRecorder:', e);
    return;
  }

  console.log('Created MediaRecorder', mediaRecorder, 'with options', options);

  mediaRecorder.onstop = (event) => {
    console.log('Recorder stopped: ', event);
    console.log('Recorded Blobs: ', recordedBlobs);
    download()
  };
  mediaRecorder.ondataavailable = handleDataAvailable;
  mediaRecorder.start();
  console.log('MediaRecorder started', mediaRecorder);
}

function stopRecording() {
  mediaRecorder.stop();
}


async function init(constraints) {
  try {
    const stream = await navigator.mediaDevices.getDisplayMedia(constraints);
    window.stream = stream;

  } catch (e) {
    console.error('navigator.getUserMedia error:', e);
  }
}

document.querySelector('button#start').addEventListener('click', async () => {

    const constraints = {
    video: {
      width: 1280, height: 720
    }
  };
  console.log('Using media constraints:', constraints);
  await init(constraints);
});

function download(){
    const blob = new Blob(recordedBlobs, {type: 'video/webm'});
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = 'test';
    document.body.appendChild(a);
    a.click();
  
    setTimeout(() => {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 100);
  
}