L'accesso alla fotocamera e al microfono dell'utente è possibile sulla piattaforma web con l'API Media Capture and Streams. Il metodo getUserMedia() richiede all'utente di accedere a una fotocamera e/o a un microfono per acquisire un flusso multimediale. Questo flusso può essere registrato con l'API MediaRecorder o condiviso con altri utenti tramite la rete. La registrazione può essere salvata in un file locale tramite il showOpenFilePicker() method.
L'esempio riportato di seguito mostra come registrare l'audio dal microfono dell'utente in formato WebM e salvare la registrazione nel file system dell'utente.
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();
});
Supporto browser
MediaDevices.getUserMedia()
API MediaRecorder
showSaveFilePicker() dell'API File System Access
Per approfondire
- Specifica Media Capture and Streams del W3C
- Specifica MediaStream Recording del W3C
- Specifica File System Access del WICG