Como gravar áudio com o microfone do usuário

François Beaufort
François Beaufort

É possível acessar a câmera e o microfone do usuário na plataforma da Web com a API Media Capture and Streams. O getUserMedia() método solicita que o usuário acesse uma câmera e/ou um microfone para capturar como um fluxo de mídia. Esse fluxo pode ser gravado com a API MediaRecorder ou compartilhado com outras pessoas pela rede. A gravação pode ser salva em um arquivo local usando o showOpenFilePicker() método.

O exemplo abaixo mostra como gravar áudio do microfone do usuário no formato WebM e salvar a gravação no sistema de arquivos do usuário.

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

Suporte ao navegador

MediaDevices.getUserMedia()

Browser Support

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

Source

API MediaRecorder

Browser Support

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

Source

showSaveFilePicker() da API File System Access

Browser Support

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

Source

Leitura adicional

Demonstração

Abrir demonstração