วิธีประมวลผลเสียงจากไมโครโฟนของผู้ใช้

François Beaufort
François Beaufort

แพลตฟอร์มเว็บมีMedia Capture and Streams API ที่ช่วยให้เข้าถึงกล้องและไมโครโฟนของผู้ใช้ได้ เมธอด getUserMedia() จะแจ้งให้ผู้ใช้เข้าถึงกล้องและ/หรือไมโครโฟนเพื่อบันทึกเป็นสตรีมสื่อ จากนั้นจะประมวลผลสตรีมนี้ในเธรด Web Audio แยกต่างหากด้วย AudioWorklet ซึ่งให้การประมวลผลเสียงที่มีเวลาในการตอบสนองต่ำมาก

ตัวอย่างด้านล่างแสดงวิธีประมวลผลเสียงจากไมโครโฟนของผู้ใช้ได้อย่างมีประสิทธิภาพ

let stream;

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

  // Load and execute the module script.
  await context.audioWorklet.addModule("processor.js");
  // Create an AudioWorkletNode. The name of the processor is the
  // one passed to registerProcessor() in the module script.
  const processor = new AudioWorkletNode(context, "processor");

  source.connect(processor).connect(context.destination);
  log("Your microphone audio is being used.");
});

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

  log("Your microphone audio is not used anymore.");
});
// processor.js
// This file is evaluated in the audio rendering thread
// upon context.audioWorklet.addModule() call.

class Processor extends AudioWorkletProcessor {
  process([input], [output]) {
    // Copy inputs to outputs.
    output[0].set(input[0]);
    return true;
  }
}

registerProcessor("processor", Processor);

การสนับสนุนเบราว์เซอร์

MediaDevices.getUserMedia()

Browser Support

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

Source

Web Audio

Browser Support

  • Chrome: 35.
  • Edge: 12.
  • Firefox: 25.
  • Safari: 14.1.

Source

AudioWorklet

Browser Support

  • Chrome: 66.
  • Edge: 79.
  • Firefox: 76.
  • Safari: 14.1.

Source

อ่านเพิ่มเติม

สาธิต

เปิดเดโม