5
头图
Recently, there is a need to record the screen, which is similar to the operation tutorial of recording software to demonstrate to others. I searched the recording screen on the Internet, and most of the results need to be downloaded and installed, and there are charges or advertisements. I accidentally found a website that uses a browser to record screen online. Out of curiosity, I studied the implementation method, and completed a small work that can be used to share with everyone. You can click to view it .
The website address of the found online screen recording is SOOGIF. It requires you to register and log in to use the screen recording function, and after the recording is completed, you can only get a limited number of download opportunities at no cost. Therefore, I plan to make a similar application myself.

Web API interface

To achieve this function, there are two main interfaces used:

The details of the implementation are recorded below.

Populate basic page elements

If you are familiar with some web front-end knowledge, then you will be familiar with the following:

 <p>This example shows you the contents of the selected part of your display.
Click the Start Capture button to begin.</p>
<q>点击开始捕获按钮,选择你要捕获的窗口。</q>

<p>
<button id="start">开始捕获</button>&nbsp;
<button id="stop">停止捕获</button>
<button id="recordBtn">开始录制</button>
<button id="downloadBtn">下载</button>
</p>

<video id="video" autoplay></video>
<br>

<strong>Log:</strong>
<br>
<pre id="log"></pre>

Add simple styles:

 #video {
      border: 1px solid #999;
      width: 98%;
      max-width: 860px;
}
.error {
      color: red;
}
 .warn {
      color: orange;
}
.info {
      color: darkgreen;
}

Approximate appearance of the page

JavaScript handles click button logic

First get the elements on the page and declare the relevant variables:

 const startElem = document.getElementById("start");
const stopElem = document.getElementById("stop");
const videoElem = document.getElementById("video");
const logElem = document.getElementById("log");
const recordBtn = document.getElementById("recordBtn");
const downloadBtn = document.getElementById("downloadBtn");
let captureStream = null;
let mediaRecorder = null;
let isRecording = false;
let recordedBlobs = [];

Logic that handles clicking the start capture button:

 // Options for getDisplayMedia()
const displayMediaOptions = {
  video: {
    cursor: "always"
  },
  audio: {
    echoCancellation: true,
    noiseSuppression: true,
    sampleRate: 44100
  }
};

async function startCapture(displayMediaOptions) {
  try {
    videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    captureStream = videoElem.srcObject
    dumpOptionsInfo();
  } catch(err) {
    console.error("Error: " + err);
  }
}

function dumpOptionsInfo() {
  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));
}

function stopCapture(evt) {
  let tracks = videoElem.srcObject.getTracks();
  tracks.forEach(track => track.stop());
  videoElem.srcObject = null;
  showMsg('用户停止了分享屏幕');
}

// Set event listeners for the start and stop buttons 给按钮添加监听事件
startElem.addEventListener("click", function(evt) {
  startCapture();
}, false);

stopElem.addEventListener("click", function(evt) {
  stopCapture();
}, false);

When the Start Capture button is clicked, the browser will pop up a page similar to the following:
capture
Select the browser page or window you want to record, or even the entire screen can be recorded.

When the window is selected and the share button is clicked, the data stream of the captured window will be synchronized to the video tag of our page and sampled in real time:
sample

At this point, we can record, and the logic of processing the start recording button is as follows:

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

  try {
    mediaRecorder = new MediaRecorder(captureStream, options);
  } catch (e) {
    showMsg(`创建MediaRecorder出错: ${JSON.stringify(e)}`);
    return;
  }
  recordBtn.textContent = '停止录制';
  isRecording = true;
  downloadBtn.disabled = true;
  mediaRecorder.onstop = (event) => {
    showMsg('录制停止了: ' + event);
  };
  mediaRecorder.ondataavailable = handleDataAvailable;
  mediaRecorder.start();
  showMsg('录制开始 mediaRecorder: ' + mediaRecorder);
}

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

function stopRecord() {
  isRecording = false;
  mediaRecorder.stop();
  downloadBtn.disabled = false;
  recordBtn.textContent = "开始录制";
  recordedBlobs = []
}

Handle the download button logic:

 downloadBtn.addEventListener('click', () => {
  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 = '录屏_' + new Date().getTime() + '.webm';
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  }, 100);
});

At this point, the demo of this screen recording is completed. The recorded file format is webm, you can open it in your browser.

Friends who need to use it immediately can also use the version I made directly, which has a better-looking UI. portal


来了老弟
508 声望31 粉丝

纸上得来终觉浅,绝知此事要躬行