# Table of Contents - [WebRTC 시작하기](#webrtc-) - [Testing WebRTC applications](#testing-webrtc-applications) - [Unified Plan SDP format - transition plan  |  WebRTC](#unified-plan-sdp-format-transition-plan-webrtc) - [Firebase + WebRTC の Codelab](#firebase-webrtc-codelab) - [미디어 기기 시작하기  |  WebRTC](#-webrtc) - [원격 스트림 시작하기  |  WebRTC](#-webrtc) - [데이터 채널  |  WebRTC](#-webrtc) - [Nyalakan server  |  WebRTC](#nyalakan-server-webrtc) - [אילוץ מדיה ואילוצים  |  WebRTC](#-webrtc) - [Comienza a usar las conexiones entre pares  |  WebRTC](#comienza-a-usar-las-conexiones-entre-pares-webrtc) - [Memulai WebRTC](#memulai-webrtc) - [תחילת העבודה עם WebRTC](#-webrtc) - [WebRTC スタートガイド](#webrtc-) - [Comienza a usar WebRTC](#comienza-a-usar-webrtc) --- # WebRTC 시작하기 [기본 콘텐츠로 건너뛰기](#main-content) [![WebRTC](https://www.gstatic.com/devrel-devsite/prod/v17c4f87be230ffee20589ee6dca0a2318ead9eddb228ec5c58233202ff69a933/webrtc/images/lockup.svg)](/) / * English * Deutsch * Español * Español – América Latina * Français * Indonesia * Italiano * Polski * Português * Português – Brasil * Tiếng Việt * Türkçe * Русский * עברית * العربيّة * فارسی * हिंदी * বাংলা * ภาษาไทย * 中文 – 简体 * 中文 – 繁體 * 日本語 * 한국어 로그인 Google은 흑인 공동체를 위한 인종적 평등을 추구하기 위해 노력하고 있습니다. [자세히 알아보기](https://google.com/racialequity?hl=ko) ![](https://webrtc.org/_static/images/translated.svg?hl=ko) 이 페이지는 [Cloud Translation API](//cloud.google.com/translate/?hl=ko) 를 통해 번역되었습니다. * [WebRTC](https://webrtc.org/?hl=ko) * [가이드](https://webrtc.org/getting-started/overview?hl=ko) WebRTC 시작하기 ============= API에 익숙하지 않다면 WebRTC 기술을 기반으로 새 애플리케이션을 만들기가 어려울 수 있습니다. 이 섹션에서는 이를 해결하기 위한 여러 일반적인 사용 사례와 코드 스니펫을 설명하여 WebRTC 표준의 다양한 API를 시작하는 방법을 설명합니다. WebRTC API ---------- WebRTC 표준은 크게 두 가지 기술, 즉 미디어 캡처 기기와 P2P 연결을 다룹니다. 미디어 캡처 기기에는 동영상 카메라와 마이크는 물론 화면 캡처 및 기기도 포함됩니다. 카메라와 마이크의 경우 `navigator.mediaDevices.getUserMedia()`를 사용하여 `MediaStreams`를 캡처합니다. 화면 녹화에는 `navigator.mediaDevices.getDisplayMedia()`를 대신 사용합니다. P2P 연결은 `RTCPeerConnection` 인터페이스에서 처리합니다. 이는 WebRTC에서 두 피어 간의 연결을 설정하고 제어하는 중심점입니다. 달리 명시되지 않는 한 이 페이지의 콘텐츠에는 [Creative Commons Attribution 4.0 라이선스](https://creativecommons.org/licenses/by/4.0/) 에 따라 라이선스가 부여되며, 코드 샘플에는 [Apache 2.0 라이선스](https://www.apache.org/licenses/LICENSE-2.0) 에 따라 라이선스가 부여됩니다. 자세한 내용은 [Google Developers 사이트 정책](https://developers.google.com/site-policies?hl=ko) 을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다. 최종 업데이트: 2019-05-28(UTC) --- # Testing WebRTC applications [Skip to main content](#main-content) [![WebRTC](https://www.gstatic.com/devrel-devsite/prod/v17c4f87be230ffee20589ee6dca0a2318ead9eddb228ec5c58233202ff69a933/webrtc/images/lockup.svg)](/) / * English * Deutsch * Español * Español – América Latina * Français * Indonesia * Italiano * Polski * Português * Português – Brasil * Tiếng Việt * Türkçe * Русский * עברית * العربيّة * فارسی * हिंदी * বাংলা * ภาษาไทย * 中文 – 简体 * 中文 – 繁體 * 日本語 * 한국어 Sign in Google is committed to advancing racial equity for Black communities. [See how.](https://google.com/racialequity) * [WebRTC](https://webrtc.org/) * [Guides](https://webrtc.org/getting-started/overview) Testing WebRTC applications ============================= When writing automated tests for your WebRTC applications, there are useful configurations that can be enabled for browsers that make development and testing easier. Chrome ------ When running automated tests on Chrome, the following arguments are useful when launching: * `--allow-file-access-from-files` - Allows API access for file:// URLs * `--disable-translate` - Disables the translation popup * `--use-fake-ui-for-media-stream` - Provide fake media streams. Useful when running on CI servers. * `--use-file-for-fake-audio-capture=` - Provide a file to use when capturing audio. * `--use-file-for-fake-video-capture=` - Provide a file to use when capturing video. * `--headless` - Run in headless mode. Useful when running on CI servers. * `--mute-audio` - Mute audio output. Firefox ------- When running automated tests on Firefox, we need to provide a set of preference keys that will be used on the launched instance. Below is the configuration used for the WebRTC samples automated tests: "prefs": { "browser.cache.disk.enable": false, "browser.cache.disk.capacity": 0, "browser.cache.disk.smart_size.enabled": false, "browser.cache.disk.smart_size.first_run": false, "browser.sessionstore.resume_from_crash": false, "browser.startup.page": 0, "media.navigator.streams.fake": true, "media.navigator.permission.disabled": true, "device.storage.enabled": false, "media.gstreamer.enabled": false, "browser.startup.homepage": "about:blank", "browser.startup.firstrunSkipsHomepage": false, "extensions.update.enabled": false, "app.update.enabled": false, "network.http.use-cache": false, "browser.shell.checkDefaultBrowser": false } Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/) , and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0) . For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies) . Java is a registered trademark of Oracle and/or its affiliates. Last updated 2019-05-28 UTC. --- # Unified Plan SDP format - transition plan  |  WebRTC [Skip to main content](#main-content) [![WebRTC](https://www.gstatic.com/devrel-devsite/prod/v17c4f87be230ffee20589ee6dca0a2318ead9eddb228ec5c58233202ff69a933/webrtc/images/lockup.svg)](/) / * English * Deutsch * Español * Español – América Latina * Français * Indonesia * Italiano * Polski * Português * Português – Brasil * Tiếng Việt * Türkçe * Русский * עברית * العربيّة * فارسی * हिंदी * বাংলা * ภาษาไทย * 中文 – 简体 * 中文 – 繁體 * 日本語 * 한국어 Sign in Google is committed to advancing racial equity for Black communities. [See how.](https://google.com/racialequity) * [WebRTC](https://webrtc.org/) * [Guides](https://webrtc.org/getting-started/overview) Unified Plan SDP format - transition plan =========================================== Google is planning to transition Chrome’s WebRTC implementation from the current SDP format (called “Plan B”) to a standards conformant format (“Unified Plan”, draft-ietf-rtcweb-jsep) over the next couple of quarters. The plan involves 5 phases, and one transient API feature. Who will be affected -------------------- People who use multiple audio tracks or multiple video tracks on a single PeerConnection will have to test their product under Unified Plan, and adapt accordingly. In the case where a call is initiated from a non-Chrome endpoint and replied to by Chrome, the form of the offer may have to change. People who do detailed SDP parsing and care about msid attributes will have to check that their parsing code picks up the new format (a=msid). The details on whether changes will be needed and how the apps need to change will be application dependent. We think that almost all applications that use only a single audio and a single video track per RTCPeerConnection will be unaffected by the change. The API feature --------------- We are adding one new feature to the RTCPeerConnection’s RTCConfiguration: enum SdpSemantics { "plan-b", "unified-plan" }; partial dictionary RTCConfiguration { SdpSemantics sdpSemantics; } The RTCConfiguration can be passed to the constructor of an RTCPeerConnection, and all offers and answers constructed will be in the Unified Plan format. Calls to setLocalDescription and setRemoteDescription will also expect the SDP to be in the Unified Plan format; if it is in the legacy Chrome format, then all but the first audio track and the first video track will be ignored. There’s also a command line flag (–enable-features=RTCUnifiedPlanByDefault in Chrome M71 and above, –enable-blink-features=RTCUnifiedPlanByDefault in earlier versions) that allows the default value of this flag to be set to “unified-plan”. The Phases ---------- ### Phase 1: Implement Unified Plan In this phase, Unified Plan was being developed behind an experimentation flag available since M65. Until phase 2, it was wisest to test with Chrome Canary using “–enable-blink-features=RTCUnifiedPlan”. ### Phase 2: Make the API feature generally available Released in M69 (beta August 2018, stable September 2018) In this phase, the default value of the sdpSemantics flag was “plan-b”. In Phase 2, people who had implementations that depended on the SDP format were expected to run tests to see if their applications work when Unified Plan is in use. For applications that support Firefox, we expect this to be a very simple exercise: just do as you would do for Firefox. The default value of the sdpSemantics flag can be changed in “chrome://flags”; look for the feature “WebRTC: Use Unified Plan SDP Semantics by default”. ### Phase 3: Switch the default The date for the switch was M72 (beta December 2018, stable January 2019). In this phase, we changed the default value of the sdpSemantics flag to “unified-plan”. Applications that discovered that they needed more time to convert set the sdpSemantics flag explicitly to “plan-b” in order to recover previous behaviour. ### Phase 4: Make “Plan B” throw In this phase, setting the sdpSemantics flag to "plan-b" results in an exception being thrown. It has been throwing in Canary from M93. As of M96, the exception was throwing in all channels, including Stable. During this phase, a [Deprecation Trial](https://developer.chrome.com/origintrials/#/view_trial/3892235977954951169) was available that allowed using Plan B without the exception throwing but the trial stopped working on May 25, 2022. ### Phase 5: Remove “Plan B” from Chromium After the trial has ended, Plan B will be removed from Chrome. At this point, the sdpSemantics flag will be removed. Attempting to set it to "plan-b" will not throw an exception, but it will no longer have any effect. Plan B is still available behind special flags or special builds but the full code removal will happen in H2, 2022. ### Phase 6: Deprecate and remove ”Plan B” from WebRTC Plan B is already marked as deprecated in WebRTC, but it is still available. Removal should happen in 2023. Preparing Your Application For Unified Plan ------------------------------------------- For detailed information about Plan B and Unified Plan differences and how your application may need to be updated in preparation for Unified plan, see the [“Unified Plan” Transition Guide (JavaScript)](https://docs.google.com/document/d/1-ZfikoUtoJa9k-GZG1daN0BU3IjIanQ_JSscHxQesvU/edit?usp=sharing) For native (C++) applications, see the document [“Migrating your native/mobile application to Unified Plan”](https://docs.google.com/document/d/1PPHWV6108znP1tk_rkCnyagH9FK205hHeE9k5mhUzOg/edit#heading=h.cp7krlgejmby) Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/) , and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0) . For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies) . Java is a registered trademark of Oracle and/or its affiliates. Last updated 2022-07-04 UTC. --- # Firebase + WebRTC の Codelab [メイン コンテンツにスキップ](#main-content) [![WebRTC](https://www.gstatic.com/devrel-devsite/prod/v17c4f87be230ffee20589ee6dca0a2318ead9eddb228ec5c58233202ff69a933/webrtc/images/lockup.svg)](/) / * English * Deutsch * Español * Español – América Latina * Français * Indonesia * Italiano * Polski * Português * Português – Brasil * Tiếng Việt * Türkçe * Русский * עברית * العربيّة * فارسی * हिंदी * বাংলা * ภาษาไทย * 中文 – 简体 * 中文 – 繁體 * 日本語 * 한국어 ログイン Google は、黒人コミュニティのための人種的公平の促進に取り組んでいます。[詳細](https://google.com/racialequity?hl=ja) をご覧ください。 ![](https://webrtc.org/_static/images/translated.svg?hl=ja) このページは [Cloud Translation API](//cloud.google.com/translate/?hl=ja) によって翻訳されました。 * [WebRTC](https://webrtc.org/?hl=ja) * [ガイド](https://webrtc.org/getting-started/overview?hl=ja) Firebase + WebRTC の Codelab ============================= 1\. はじめに -------- この Codelab では、 ブラウザで WebRTC API を使用し、シグナリングに Cloud Firestore を使用する必要があります。「 これは FirebaseRTC と呼ばれる簡単な例です。 WebRTC 対応アプリケーションを構築するための基本を学びました。 > ### 学習内容 * WebRTC を使用してウェブ アプリケーションでビデオ通話を開始する * Cloud Firestore を使用したリモート パーティへのシグナリング ### 必要なもの この Codelab を開始する前に、以下がインストールされていることを確認してください。 * npm(通常 Node.js に付属)- Node LTS を推奨 2\. Firebase プロジェクトを作成して設定する ---------------------------- ### Firebase プロジェクトを作成する 1. [Firebase コンソール](https://console.firebase.google.com?hl=ja) で \[追加\] をクリックします。 Firebase プロジェクトに「FirebaseRTC」という名前を付けます。 Firebase プロジェクトのプロジェクト ID を覚えておいてください。 > 1. \[プロジェクトを作成\] をクリックします。 これから作成するアプリケーションでは、利用可能な 2 つの Firebase サービスを使用します。 ウェブの場合: * 構造化データを Cloud に保存し、すぐに使える Cloud Firestore データが更新されると通知が送信されます。 * 静的アセットをホストして提供する Firebase Hosting この Codelab では、Firebase Hosting をすでに プロジェクトを指定します。Cloud Firestore については Firebase コンソールを使用してサービスの構成と有効化を行う。 ### Cloud Firestore の有効化 このアプリは Cloud Firestore を使用してチャット メッセージを保存し、新しいチャットを受信します ブロックすることもできます。 Cloud Firestore を有効にする必要があります。 1. Firebase コンソール メニューの \[開発\] セクションで、\[データベース\] をクリックします。 2. \[Cloud Firestore\] ペインで \[**データベースを作成**\] をクリックします。 3. \[**テストモードで開始**\] オプションを選択し、 セキュリティ ルールに関する免責条項 テストモードでは、開発中にデータベースに自由に書き込めます。 データベースは後ほど、この Codelab でより安全にします。 3\. サンプルコードを取得する ---------------- コマンドラインから GitHub リポジトリのクローンを作成します。 git clone https://github.com/webrtc/FirebaseRTC サンプルコードのクローンが `FirebaseRTC` ディレクトリにすでに作成されているはずです。 今後は、このディレクトリからコマンドラインが実行されるようにしてください。 cd FirebaseRTC ### スターター アプリをインポートする エディタで `FirebaseRTC` でファイルを開き、 手順は次のとおりです。このディレクトリには、Terraform の この Codelab は、まだ機能していない WebRTC アプリで構成されています。Google が実現 この Codelab 全体を通して使います。 4\. Firebase コマンドライン インターフェースをインストールする -------------------------------------- Firebase コマンドライン インターフェース(CLI)を使用すると、ウェブアプリを提供できます ウェブアプリを Firebase Hosting にデプロイします。 > 1. 次の npm コマンドを実行して CLI をインストールします。 `sh npm -g install firebase-tools` で確認できます。 > 1. 次のコマンドを実行して、CLI が正しくインストールされていることを確認します。 command: `sh firebase --version` Firebase CLI のバージョンが v6.7.1 以降であることを確認します。 1. 次のコマンドを実行して、Firebase CLI を承認します。 `sh firebase login` Firebase 用のアプリの構成を pull するようにウェブアプリ テンプレートを設定できました アプリのローカル ディレクトリとファイルからのホスティング。しかし、そのためには アプリを Firebase プロジェクトに関連付けます。 1. 次のコマンドを実行して、アプリを Firebase プロジェクトに関連付けます。 command: `sh firebase use --add` 2. プロンプトが表示されたら、プロジェクト ID を選択し、Firebase プロジェクトにプロジェクト名を入力します。 使用します。 エイリアスは、複数の環境(本番環境、ステージング環境など)がある場合に役立ちます。 ただし、この Codelab では `default` のエイリアスを使用します。 1. コマンドラインの残りの手順に沿って操作します。 5\. ローカル サーバーを実行する ------------------ これでアプリの作成を開始する準備が整いました。アプリをローカルで実行しましょう。 1. 次の Firebase CLI コマンドを実行します。 `sh firebase serve --only hosting` 2. コマンドラインに次のレスポンスが表示されます。 `hosting: Local server: http://localhost:5000` Firebase Hosting エミュレータを使用して、アプリをローカルで配信します。ウェブアプリ http://localhost:5000 からアクセスできるはずです。 1. http://localhost:5000 でアプリを開きます。 インスタンスにリンクされた FirebaseRTC のコピーが表示されます。 Firebase プロジェクト。 アプリが自動的に Firebase プロジェクトに接続されます。 6\. 新しい部屋を作成する -------------- このアプリケーションでは、各ビデオチャット セッションを「チャットルーム」と呼びます。ユーザーは 新しいルームに入室するには、これにより ID が生成されます 同じ部屋に参加するための 2 つのネットワーク名を指定します。ID が鍵として使用されます。 Cloud Firestore にエクスポートして、 各部屋には、オファーと特典の `RTCSessionDescriptions` が含まれます さらに、各政党の ICE 候補者を含む 2 つのコレクションも返されます。 あなたの最初のタスクは、不足しているコードを実装して、 最初のオファーを提示する必要があります。`public/app.js` を開き、`// Add code for creating a room here` というコメントを見つけて、次のコードを追加します。 const offer = await peerConnection.createOffer(); await peerConnection.setLocalDescription(offer); const roomWithOffer = { offer: { type: offer.type, sdp: offer.sdp } } const roomRef = await db.collection('rooms').add(roomWithOffer); const roomId = roomRef.id; document.querySelector('#currentRoom').innerText = `Current room is ${roomId} - You are the caller!` 1 行目で、オファーを表す `RTCSessionDescription` を作成します。 渡されます。これをローカルの説明として設定し、 新しい Room オブジェクトが作成されます。 次に、データベースに対する変更をリッスンし、Google Cloud からの応答が 追加されたことを示します。 roomRef.onSnapshot(async snapshot -> { console.log('Got updated room:', snapshot.data()); const data = snapshot.data(); if (!peerConnection.currentRemoteDescription && data.answer) { console.log('Set remote description: ', data.answer); const answer = new RTCSessionDescription(data.answer) await peerConnection.setRemoteDescription(answer); } }); これは、呼び出し先が `RTCSessionDescription` を書き込むまで待機します。 それを発信者のリモートの説明として設定します `RTCPeerConnection`。 7\. チャットルームへの参加 --------------- 次のステップでは、既存のチャットルームに参加するためのロジックを実装します。ユーザー これを行うには、\[**チャットルームに参加**\] ボタンをクリックしてチャットルームの ID を入力します。 選択します。ここでのタスクは、Terraform ワークフローの 回答に対する `RTCSessionDescription`。データベースの部屋を更新します。 必要があります。 const offer = roomSnapshot.data().offer; await peerConnection.setRemoteDescription(offer); const answer = await peerConnection.createAnswer(); await peerConnection.setLocalDescription(answer); const roomWithAnswer = { answer: { type: answer.type, sdp: answer.sdp } } await roomRef.update(roomWithAnswer); 上記のコードでは、まず呼び出し元から特典を抽出し、 リモートの説明として設定する `RTCSessionDescription`。次に ローカルの説明として設定し、データベースを更新します。更新 データベースが呼び出し元側で `onSnapshot` コールバックをトリガーし、 呼び出し先からの応答に基づいてリモートの説明を設定します。 これで、インスタンス間での `RTCSessionDescription` オブジェクトの交換が完了しました。 あります。 8\. ICE の候補者を集める ---------------- 発信者と受信者が互いに接続するには、以下も行う必要があります。 WebRTC にリモートピアへの接続方法を指示する ICE 候補を交換します。 次のタスクでは、ICE の候補をリッスンして Google Cloud の データベース内のコレクションに追加します関数 `collectIceCandidates` を見つけます。 次のコードを追加します。 async function collectIceCandidates(roomRef, peerConnection, localName, remoteName) { const candidatesCollection = roomRef.collection(localName); peerConnection.addEventListener('icecandidate', event -> { if (event.candidate) { const json = event.candidate.toJSON(); candidatesCollection.add(json); } }); roomRef.collection(remoteName).onSnapshot(snapshot -> { snapshot.docChanges().forEach(change -> { if (change.type === "added") { const candidate = new RTCIceCandidate(change.doc.data()); peerConnection.addIceCandidate(candidate); } }); }) } この関数は 2 つのことを行います。WebRTC API から ICE 候補を収集し、 それらがデータベースに追加され、追加された ICE 候補がリモートからリッスンされます。 その `RTCPeerConnection` インスタンスに追加します。重要なのは データベースの変更をリッスンし、新しく追加されたものでないものを除外します。 同じ ICE 候補の集合が何度も追加されてしまうためです。 \] をクリックします。 9\. まとめ ------- この Codelab では、Cloud Functions を使用して WebRTC のシグナリングを実装する方法を学習しました。 Firestore を使用して簡単なビデオチャットを作成する方法も説明しました。 説明します。 詳しくは以下のページをご覧ください。 1. [FirebaseRTC ソースコード](https://github.com/webrtc/FirebaseRTC) 2. [WebRTC のサンプル](https://webrtc.github.io/samples) 3. [Cloud Firestore](https://firebase.google.com/docs/firestore/?hl=ja) 特に記載のない限り、このページのコンテンツは[クリエイティブ・コモンズの表示 4.0 ライセンス](https://creativecommons.org/licenses/by/4.0/) により使用許諾されます。コードサンプルは [Apache 2.0 ライセンス](https://www.apache.org/licenses/LICENSE-2.0) により使用許諾されます。詳しくは、[Google Developers サイトのポリシー](https://developers.google.com/site-policies?hl=ja) をご覧ください。Java は Oracle および関連会社の登録商標です。 最終更新日 2024-08-22 UTC。 --- # 미디어 기기 시작하기  |  WebRTC [기본 콘텐츠로 건너뛰기](#main-content) [![WebRTC](https://www.gstatic.com/devrel-devsite/prod/v17c4f87be230ffee20589ee6dca0a2318ead9eddb228ec5c58233202ff69a933/webrtc/images/lockup.svg)](/) / * English * Deutsch * Español * Español – América Latina * Français * Indonesia * Italiano * Polski * Português * Português – Brasil * Tiếng Việt * Türkçe * Русский * עברית * العربيّة * فارسی * हिंदी * বাংলা * ภาษาไทย * 中文 – 简体 * 中文 – 繁體 * 日本語 * 한국어 로그인 Google은 흑인 공동체를 위한 인종적 평등을 추구하기 위해 노력하고 있습니다. [자세히 알아보기](https://google.com/racialequity?hl=ko) ![](https://webrtc.org/_static/images/translated.svg?hl=ko) 이 페이지는 [Cloud Translation API](//cloud.google.com/translate/?hl=ko) 를 통해 번역되었습니다. * [WebRTC](https://webrtc.org/?hl=ko) * [가이드](https://webrtc.org/getting-started/overview?hl=ko) 미디어 기기 시작하기 ============= 웹용으로 개발할 때 WebRTC 표준은 컴퓨터 또는 스마트폰에 연결된 카메라 및 마이크입니다. 이 기기 일반적으로 미디어 기기라고 하며 JavaScript를 사용하여 액세스할 수 있습니다. `MediaDevices`를 구현하는 `navigator.mediaDevices` 객체를 통해 인터페이스에 추가되었습니다. 이 객체에서 연결된 모든 장치를 열거하고 기기가 변경되거나 (기기가 연결되거나 연결 해제되었을 때) 기기가 열릴 때 를 호출하여 미디어 스트림을 검색합니다 (아래 참조). 가장 일반적인 방법은 `getUserMedia()` 함수를 통하는 것입니다. 일치하는 미디어의 `MediaStream`로 확인되는 프로미스를 반환합니다. 기기에서 사용할 수 있습니다. 이 함수는 단일 `MediaStreamConstraints` 객체를 사용합니다. Google의 요구사항을 나타냅니다 예를 들어 간단히 기본 마이크와 카메라가 있다면 다음과 같이 합니다. ### 프라미스 사용 const constraints = { 'video': true, 'audio': true } navigator.mediaDevices.getUserMedia(constraints) .then(stream => { console.log('Got MediaStream:', stream); }) .catch(error => { console.error('Error accessing media devices.', error); }); ### async/await 사용 const openMediaDevices = async (constraints) => { return await navigator.mediaDevices.getUserMedia(constraints); } try { const stream = openMediaDevices({'video':true,'audio':true}); console.log('Got MediaStream:', stream); } catch(error) { console.error('Error accessing media devices.', error); } `getUserMedia()`를 호출하면 권한 요청이 트리거됩니다. 사용자가 권한을 허용하면 프로미스가 다음을 포함하는 `MediaStream`로 확인됩니다. 동영상 1개와 오디오 트랙 1개가 있어야 합니다. 권한이 거부되면 `PermissionDeniedError`이 발생합니다. 일치하는 기기가 없는 경우 연결되면 `NotFoundError`이 발생합니다. `MediaDevices` 인터페이스에 대한 전체 API 참조는 [MDN 웹에서 확인할 수 있습니다. 문서](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices) 를 참조하세요. 미디어 기기 쿼리 --------- 좀 더 복잡한 애플리케이션의 경우 마이크와 연결된 카메라와 마이크를 통해 적절한 피드백을 있습니다. `enumerateDevices()` 함수를 호출하면 됩니다. 이렇게 하면 다음을 설명하는 `MediaDevicesInfo`의 배열로 확인되는 프로미스를 반환합니다. 각 알려진 미디어 기기가 포함됩니다 이를 사용하여 사용자에게 UI를 표시하고 원하는 것을 선택할 수 있습니다. 각 `MediaDevicesInfo`에는 `kind`를 나타내는 `audioinput`, `audiooutput` 또는 `videoinput` 값 지정할 수 있습니다. ### 프라미스 사용 function getConnectedDevices(type, callback) { navigator.mediaDevices.enumerateDevices() .then(devices => { const filtered = devices.filter(device => device.kind === type); callback(filtered); }); } getConnectedDevices('videoinput', cameras => console.log('Cameras found', cameras)); ### async/await 사용 async function getConnectedDevices(type) { const devices = await navigator.mediaDevices.enumerateDevices(); return devices.filter(device => device.kind === type) } const videoCameras = getConnectedDevices('videoinput'); console.log('Cameras found:', videoCameras); 기기 변경사항 수신 대기 ------------- 대부분의 컴퓨터는 런타임 중에 다양한 기기 연결을 지원합니다. 그것은 USB, 블루투스 헤드셋 또는 외부 스피커 세트로 연결된 웹캠 포함 이를 적절히 지원하려면 웹 응용 프로그램이 변경 사항을 수신 대기하고 미디어 기기입니다 이렇게 하려면 `devicechange` 이벤트의 경우 `navigator.mediaDevices` // Updates the select element with the provided set of cameras function updateCameraList(cameras) { const listElement = document.querySelector('select#availableCameras'); listElement.innerHTML = ''; cameras.map(camera => { const cameraOption = document.createElement('option'); cameraOption.label = camera.label; cameraOption.value = camera.deviceId; }).forEach(cameraOption => listElement.add(cameraOption)); } // Fetch an array of devices of a certain type async function getConnectedDevices(type) { const devices = await navigator.mediaDevices.enumerateDevices(); return devices.filter(device => device.kind === type) } // Get the initial set of cameras connected const videoCameras = getConnectedDevices('videoinput'); updateCameraList(videoCameras); // Listen for changes to media devices and update the list accordingly navigator.mediaDevices.addEventListener('devicechange', event => { const newCameraList = getConnectedDevices('video'); updateCameraList(newCameraList); }); 미디어 제약 조건 --------- `MediaStreamConstraints`를 구현해야 하는 제약 조건 객체 인터페이스에 있는 경우, `getUserMedia()`에 매개변수로 전달하면 특정 요구사항과 일치하는 미디어 기기를 선택합니다. 이러한 요구사항은 느슨하게 정의 (오디오 또는 동영상)되거나 매우 구체적 (최소 카메라) 해상도 또는 정확한 기기 ID). kubectl 명령어를 사용하는 애플리케이션은 `getUserMedia()` API는 먼저 기존 기기를 확인한 다음 `deviceId` 제약 조건을 사용하여 정확한 기기와 일치하는 제약 조건. 또한 기기는 가능한 경우 제약 조건에 따라 구성됩니다. 마이크에서 에코 취소를 사용 설정하거나 특정 또는 최소 너비를 설정할 수 있습니다. 카메라의 동영상 및 높이입니다. async function getConnectedDevices(type) { const devices = await navigator.mediaDevices.enumerateDevices(); return devices.filter(device => device.kind === type) } // Open camera with at least minWidth and minHeight capabilities async function openCamera(cameraId, minWidth, minHeight) { const constraints = { 'audio': {'echoCancellation': true}, 'video': { 'deviceId': cameraId, 'width': {'min': minWidth}, 'height': {'min': minHeight} } } return await navigator.mediaDevices.getUserMedia(constraints); } const cameras = getConnectedDevices('videoinput'); if (cameras && cameras.length > 0) { // Open first available video camera with a resolution of 1280x720 pixels const stream = openCamera(cameras[0].deviceId, 1280, 720); } `MediaStreamConstraints` 인터페이스에 관한 전체 문서는 확인할 수 있습니다. ([MDN 웹) 문서](https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints) 를 참조하세요. 로컬 재생 ----- 미디어 기기가 열리고 `MediaStream`를 사용할 수 있게 되면 동영상 또는 오디오 요소에 할당하여 로컬에서 스트림을 재생할 수 있습니다. async function playVideoFromCamera() { try { const constraints = {'video': true, 'audio': true}; const stream = await navigator.mediaDevices.getUserMedia(constraints); const videoElement = document.querySelector('video#localVideo'); videoElement.srcObject = stream; } catch(error) { console.error('Error opening video camera.', error); } } `getUserMedia()`와 함께 사용되는 일반적인 동영상 요소에 필요한 HTML은 보통 `autoplay` 및 `playsinline` 속성이 있습니다. `autoplay` 속성을 사용하면 요소에 할당된 새 스트림이 자동으로 재생됩니다. `playsinline` 속성을 사용하면 동영상을 전체가 아닌 인라인으로 재생할 수 있습니다. 일부 모바일 브라우저의 경우 또한 라이브 스트림의 경우 `controls="false"`(사용자가 일시중지할 수 있어야 하는 경우 제외) 있습니다. Local video playback