Dostęp do urządzeń multimedialnych użytkownika
Dowiedzą się Państwo, jak używać `navigator.mediaDevices.getUserMedia()` do uzyskiwania dostępu do kamery i mikrofonu użytkownika w przeglądarce internetowej.
Dostęp do urządzeń multimedialnych użytkownika to bezpłatna lekcja Real-Time Streaming Systems (WebRTC + Live Data) na CoddyKit. To lekcja 1 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Real-Time Streaming Systems (WebRTC + Live Data), a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Real-Time Streaming Systems (WebRTC + Live Data) zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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.
Często zadawane pytania
Czy lekcja „Dostęp do urządzeń multimedialnych użytkownika” jest bezpłatna?
Tak — pełny tekst „Dostęp do urządzeń multimedialnych użytkownika” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Real-Time Streaming Systems (WebRTC + Live Data), przejdź na CoddyKit PRO. Kurs Real-Time Streaming Systems (WebRTC + Live Data) zawiera 4 lekcji w sumie.
Co nauczysz się w „Dostęp do urządzeń multimedialnych użytkownika”?
Dowiedzą się Państwo, jak używać `navigator.mediaDevices.getUserMedia()` do uzyskiwania dostępu do kamery i mikrofonu użytkownika w przeglądarce internetowej. Ćwiczysz Real-Time Streaming Systems (WebRTC + Live Data) z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Real-Time Streaming Systems (WebRTC + Live Data)?
Nie wymagamy żadnego doświadczenia. Real-Time Streaming Systems (WebRTC + Live Data) w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 1 z 4.
Ile czasu zajmuje lekcja „Dostęp do urządzeń multimedialnych użytkownika”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Real-Time Streaming Systems (WebRTC + Live Data)?
Tak. Każda lekcja Real-Time Streaming Systems (WebRTC + Live Data) zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Dostęp do urządzeń multimedialnych użytkownika
- Dodawanie i usuwanie ścieżek multimedialnych
- Wyświetlanie zdalnego dźwięku i obrazu
- Sterowanie jakością mediów i ograniczeniami