如何录制用户的屏幕

François Beaufort
François Beaufort

借助 Screen Capture API,可以在 Web 平台上共享标签页、窗口和屏幕。借助 getDisplayMedia() 方法,用户可以选择要捕获的屏幕作为媒体流。然后,可以使用 MediaRecorder API 记录此视频流,也可以通过网络与他人分享。可以通过 showOpenFilePicker() 方法将录制内容保存到本地文件。

以下示例展示了如何以 WebM 格式录制用户屏幕,在同一页面上进行本地预览,并将录制内容保存到用户的文件系统中。

let stream;
let recorder;

shareScreenButton.addEventListener("click", async () => {
  // Prompt the user to share their screen.
  stream = await navigator.mediaDevices.getDisplayMedia();
  recorder = new MediaRecorder(stream);
  // Preview the screen locally.
  video.srcObject = stream;
});

stopShareScreenButton.addEventListener("click", () => {
  // Stop the stream.
  stream.getTracks().forEach(track => track.stop());
  video.srcObject = null;
});

startRecordButton.addEventListener("click", async () => {
  // For the sake of more legible code, this sample only uses the
  // `showSaveFilePicker()` method. In production, you need to
  // cater for browsers that don't support this method, as
  // outlined in https://web.dev/patterns/files/save-a-file/.

  // Prompt the user to choose where to save the recording file.
  const suggestedName = "screen-recording.webm";
  const handle = await window.showSaveFilePicker({ suggestedName });
  const writable = await handle.createWritable();

  // Start recording.
  recorder.start();
  recorder.addEventListener("dataavailable", async (event) => {
    // Write chunks to the file.
    await writable.write(event.data);
    if (recorder.state === "inactive") {
      // Close the file when the recording stops.
      await writable.close();
    }
  });
});

stopRecordButton.addEventListener("click", () => {
  // Stop the recording.
  recorder.stop();
});

浏览器支持

MediaDevices.getDisplayMedia()

Browser Support

  • Chrome: 72.
  • Edge: 79.
  • Firefox: 66.
  • Safari: 13.

Source

MediaRecorder API

Browser Support

  • Chrome: 47.
  • Edge: 79.
  • Firefox: 25.
  • Safari: 14.1.

Source

File System Access API 的 showSaveFilePicker()

Browser Support

  • Chrome: 86.
  • Edge: 86.
  • Firefox: not supported.
  • Safari: not supported.

Source

深入阅读

演示

打开演示