WebRTC (Web Real-Time Communication) は、シンプルなアプリケーション プログラミング インターフェイス (API) を介して Web ブラウザーとモバイル アプリケーションにリアルタイム通信を提供する無料のオープンソース プロジェクトです。追加のプラグインやサードパーティ ソフトウェアを必要とせずに、Web ブラウザ間でオーディオ、ビデオ、データを直接共有できるようになります。 HTML5 で WebRTC を使用できるいくつかの方法を次に示します。
基本セットアップ: HTML5 で WebRTC を使用するには、必要な HTML および JavaScript コードをセットアップする必要があります。基本的な例を次に示します。
html <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebRTC Example</title>
</head>
<body>
<video id="localVideo" autoplay></video>
<video id="remoteVideo" autoplay></video>
<script>
// Your WebRTC code here
</script>
</body>
</html>
ユーザー メディアにアクセス:ユーザーのカメラとマイクにアクセスするには、 navigator.mediaDevices.getUserMediaを使用します。これはビデオとオーディオの通信に必要です。
JavaScript navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then((stream) => {
// Use the stream for local video
document.getElementById('localVideo').srcObject = stream;
})
.catch((error) => {
console.error('Error accessing media devices:', error);
});
ピア接続の作成:ピア接続をセットアップして、2 人のユーザー間の接続を確立します。
JavaScript let peerConnection = new RTCPeerConnection();
// Add local stream to the peer connection
stream.getTracks().forEach(track => peerConnection.addTrack(track, stream));
オファーと回答の作成: createOfferとcreateAnswer方法を使用して、コミュニケーション用のオファーと回答を生成します。
JavaScript // Create an offer
peerConnection.createOffer()
.then((offer) => peerConnection.setLocalDescription(offer))
.then(() => {
// Send the offer to the other peer
})
.catch((error) => console.error('Error creating offer:', error));
// On the other side, handle the offer and create an answer
// Then set the remote description of the peer connection
データ チャネルの確立: createDataChannel方法を使用して、ピア間のデータ通信を有効にします。
JavaScript let dataChannel = peerConnection.createDataChannel('myDataChannel');
dataChannel.onopen = (event) => {
// Data channel is open
};
dataChannel.onmessage = (event) => {
// Handle received data
};
ICE 候補の処理: ICE 候補の処理を実装して、異なるネットワーク間での通信を可能にします。
JavaScript peerConnection.onicecandidate = (event) => {
if (event.candidate) {
// Send the ICE candidate to the other peer
}
};
リモート ビデオ表示:リモート ピアからのビデオ ストリームを表示するようにリモート ビデオ要素を設定します。
JavaScript peerConnection.ontrack = (event) => {
document.getElementById('remoteVideo').srcObject = event.streams[0];
};
これらは単なる基本的な例であり、実際のアプリケーションにはさらに多くの機能やエラー処理が含まれる場合があります。さらに、ピア間でセッションの説明や ICE 候補などの情報を交換するためのシグナリング メカニズム (サーバーまたは WebSocket などのサービス) が必要になります。 WebRTC API は、リアルタイム通信のための堅牢なツール セットを提供するため、アプリケーションのニーズに基づいてカスタマイズおよび拡張できます。