Cách ghi âm từ micrô của người dùng

François Beaufort
François Beaufort

Bạn có thể truy cập vào camera và micrô của người dùng trên nền tảng web bằng API Truyền phát và chụp ảnh đa phương tiện. Phương thức getUserMedia() nhắc người dùng truy cập vào máy ảnh và/hoặc micrô để chụp dưới dạng luồng nội dung nghe nhìn. Sau đó, bạn có thể ghi lại luồng này bằng MediaRecorder API hoặc chia sẻ với người khác qua mạng. Bạn có thể lưu bản ghi vào một tệp cục bộ thông qua phương thức showOpenFilePicker().

Ví dụ bên dưới cho thấy cách bạn có thể ghi âm thanh từ micrô của người dùng ở định dạng WebM và lưu bản ghi vào hệ thống tệp của người dùng.

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/articles/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();
});

Hỗ trợ trình duyệt

MediaDevices.getUserMedia()

Browser Support

  • Chrome: 53.
  • Edge: 12.
  • Firefox: 36.
  • Safari: 11.

Source

MediaRecorder API

Browser Support

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

Source

showSaveFilePicker() của File System Access API

Browser Support

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

Source

Tài liệu đọc thêm

Bản minh hoạ

Mở bản minh hoạ