访问用户媒体设备
了解如何在网页浏览器中使用 `navigator.mediaDevices.getUserMedia()` 访问用户的摄像头和麦克风。
访问用户媒体设备 是 CoddyKit 上的免费 Real-Time Streaming Systems (WebRTC + Live Data) 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Real-Time Streaming Systems (WebRTC + Live Data) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Real-Time Streaming Systems (WebRTC + Live Data) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「访问用户媒体设备」课时是免费的吗?
是的 — 「访问用户媒体设备」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Real-Time Streaming Systems (WebRTC + Live Data) 课程的其余内容,请升级到 CoddyKit PRO。 Real-Time Streaming Systems (WebRTC + Live Data) 课程共包含 4 节课。
「访问用户媒体设备」这节课中我会学到什么?
了解如何在网页浏览器中使用 `navigator.mediaDevices.getUserMedia()` 访问用户的摄像头和麦克风。 你通过在浏览器中直接运行的动手代码来练习 Real-Time Streaming Systems (WebRTC + Live Data),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Real-Time Streaming Systems (WebRTC + Live Data) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Real-Time Streaming Systems (WebRTC + Live Data) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「访问用户媒体设备」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Real-Time Streaming Systems (WebRTC + Live Data) 课中编写并运行代码吗?
能。每节 Real-Time Streaming Systems (WebRTC + Live Data) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。