แพลตฟอร์มเว็บมี 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/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();
});
การสนับสนุนเบราว์เซอร์
MediaDevices.getUserMedia()
MediaRecorder API
File System Access API's showSaveFilePicker()
อ่านเพิ่มเติม
- ข้อกำหนดเฉพาะของ W3C Media Capture and Streams
- ข้อกำหนดเฉพาะของ W3C MediaStream Recording
- ข้อกำหนดเฉพาะของ WICG File System Access