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 đó, luồng này có thể được xử lý trong một luồng Web Audio riêng biệt bằng AudioWorklet. Luồng này cung cấp khả năng xử lý âm thanh có độ trễ rất thấp.
Ví dụ bên dưới cho thấy cách bạn có thể xử lý âm thanh từ micrô của người dùng một cách hiệu quả.
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);
Hỗ trợ trình duyệt
MediaDevices.getUserMedia()
Web Audio
AudioWorklet
Tài liệu đọc thêm
- Quy cách về tính năng chụp ảnh và truyền phát nội dung nghe nhìn của W3C
- Quy cách âm thanh trên web của W3C
- Nhập AudioWorklet