如何通过用户麦克风录制音频

François Beaufort
François Beaufort

在 Web 平台上,可通过 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

来源

深入阅读

演示

打开演示