如何錄製使用者的螢幕(')

François Beaufort
François Beaufort

網頁平台可透過 Screen Capture API 分享分頁、視窗和畫面。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

延伸閱讀

示範

開啟試用版