如何錄製使用者的麥克風音訊(')

François Beaufort
François Beaufort

透過 Media Capture and Streams API,您可以在網路平台上存取使用者的相機和麥克風。getUserMedia() 方法會提示使用者存取相機和/或麥克風,以擷取媒體串流。接著,你可以使用 MediaRecorder API 錄製這個串流,或透過網路與他人分享。您可以透過 showOpenFilePicker() 方法,將錄製內容儲存至本機檔案。

以下範例說明如何以 WebM 格式錄製使用者的麥克風音訊,並將錄音儲存到使用者的檔案系統。

let stream;
let recorder;

startMicrophoneButton.addEventListener("click", async () => {
  // Prompt the user to use their microphone.
  stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  recorder = new MediaRecorder(stream);
});

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

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 = "microphone-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.getUserMedia()

瀏覽器支援

  • 53
  • 12
  • 36
  • 11

資料來源

MediaRecorder API

瀏覽器支援

  • 47
  • 79
  • 25
  • 14.1

資料來源

File System Access API 的 showSaveFilePicker()

瀏覽器支援

  • 86
  • 86
  • x
  • x

資料來源

其他資訊

操作示範

開啟示範模式