Accesso ai dispositivi multimediali dell'utente
Scopra come usare `navigator.mediaDevices.getUserMedia()` per accedere alla fotocamera e al microfono dell'utente in un browser web.
Accesso ai dispositivi multimediali dell'utente è una lezione Real-Time Streaming Systems (WebRTC + Live Data) gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Real-Time Streaming Systems (WebRTC + Live Data), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Real-Time Streaming Systems (WebRTC + Live Data) include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Get User's Camera & Mic
Welcome! In this lesson, we'll learn how to access a user's camera and microphone directly from their web browser. This is the first step for any real-time video or audio application.
We'll use a powerful Web API called navigator.mediaDevices.getUserMedia().
Why getUserMedia?
getUserMedia() is a core WebRTC feature. It allows your web application to:
- Capture audio from a microphone.
- Capture video from a camera.
- Access these streams as
MediaStreamobjects.
These streams can then be displayed, recorded, or sent to other peers.
User Permissions are Key
Before your app can access any media devices, the browser must ask the user for permission. This is a crucial security and privacy feature.
- A prompt will appear asking to "Allow" or "Block" camera/microphone access.
- Your code only runs if the user grants permission.
Requesting Media with Constraints
getUserMedia() takes a single argument: a constraints object. This object tells the browser which media types you need and any specific requirements.
You can request:
audio: truefor microphone access.video: truefor camera access.
Let's see a basic example.
Requesting Only Audio
Here's how to request only the user's microphone. If successful, the browser provides a MediaStream object containing the audio track.
We'll then log the success (or failure) of getting the stream. In a real app, you'd attach it to an <audio> element.
Live Audio Stream
Try running this example to access your microphone. Make sure your browser has permission!
async function getAudio() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
console.log('Audio stream obtained successfully!');
// In a browser, you'd typically attach this to an <audio> element:
// const audioEl = document.getElementById('localAudio');
// if (audioEl) audioEl.srcObject = stream;
} catch (err) {
console.error('Error accessing audio:', err.name, err.message);
alert('Failed to get audio. Check permissions! Error: ' + err.name);
}
}
getAudio();Requesting Only Video
Similarly, we can request only the user's camera. The resulting MediaStream will contain a video track.
This stream can then be displayed in an <video> element, allowing you to see your live camera feed.
Live Video Stream
Run this example to try accessing your camera. Remember to grant camera access when prompted!
async function getVideo() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true });
console.log('Video stream obtained successfully!');
// In a browser, you'd typically attach this to a <video> element:
// const videoEl = document.getElementById('localVideo');
// if (videoEl) {
// videoEl.srcObject = stream;
// videoEl.play();
// }
} catch (err) {
console.error('Error accessing video:', err.name, err.message);
alert('Failed to get video. Check permissions! Error: ' + err.name);
}
}
getVideo();Dealing with Errors
getUserMedia() returns a Promise that can reject. It's crucial to handle these errors gracefully.
Common error types include:
- NotAllowedError: User denied permission.
- NotFoundError: No camera/mic found.
- NotReadableError: Hardware error.
Always use a try...catch block as shown in the examples!
Quick Check: Constraints
You want to access both the user's microphone and camera. Which constraints object should you pass to getUserMedia()?
Recap: Accessing Media
Great job! You've learned how to use navigator.mediaDevices.getUserMedia() to access a user's camera and microphone.
- It requires explicit user permission.
- The
constraintsobject specifies desired media types. - Always handle potential errors with
try...catch.
Next, we'll learn how to manage these media tracks within a WebRTC peer connection.
Domande Frequenti
La lezione «Accesso ai dispositivi multimediali dell'utente» è gratuita?
Sì — il testo completo di «Accesso ai dispositivi multimediali dell'utente» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Real-Time Streaming Systems (WebRTC + Live Data), passa a CoddyKit PRO. Il corso Real-Time Streaming Systems (WebRTC + Live Data) include 4 lezioni in totale.
Cosa imparerò in «Accesso ai dispositivi multimediali dell'utente»?
Scopra come usare `navigator.mediaDevices.getUserMedia()` per accedere alla fotocamera e al microfono dell'utente in un browser web. Eserciti Real-Time Streaming Systems (WebRTC + Live Data) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Real-Time Streaming Systems (WebRTC + Live Data)?
Non è richiesta alcuna esperienza precedente. Real-Time Streaming Systems (WebRTC + Live Data) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.
Quanto tempo richiede la lezione «Accesso ai dispositivi multimediali dell'utente»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Real-Time Streaming Systems (WebRTC + Live Data)?
Sì. Ogni lezione Real-Time Streaming Systems (WebRTC + Live Data) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Accesso ai dispositivi multimediali dell'utente
- Aggiunta e rimozione delle tracce multimediali
- Visualizzazione di audio e video remoti
- Controllo della qualità dei media e dei vincoli