ユーザーメディアデバイスへのアクセス
`navigator.mediaDevices.getUserMedia()`を使って、Webブラウザーからユーザーのカメラとマイクにアクセスする方法を学びます。
「ユーザーメディアデバイスへのアクセス」はCoddyKit上の無料Real-Time Streaming Systems (WebRTC + Live Data)レッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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.
よくある質問
「ユーザーメディアデバイスへのアクセス」レッスンは無料ですか?
はい。「ユーザーメディアデバイスへのアクセス」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Real-Time Streaming Systems (WebRTC + Live Data)コースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Real-Time Streaming Systems (WebRTC + Live Data)コースには全4レッスンが含まれています。
「ユーザーメディアデバイスへのアクセス」で何を学びますか?
`navigator.mediaDevices.getUserMedia()`を使って、Webブラウザーからユーザーのカメラとマイクにアクセスする方法を学びます。 ブラウザで直接実行するハンズオンコードでReal-Time Streaming Systems (WebRTC + Live Data)を演習し、24時間対応の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フィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- ユーザーメディアデバイスへのアクセス
- メディアトラックの追加と削除
- リモート音声・動画の表示
- メディア品質と制約の制御