This will delete the page "主要的 WebRTC API和使用示例"
. Please be certain.
getUserMedia:
RTCPeerConnection:
RTCDataChannel:
以下是一个简单的示例,展示如何使用 WebRTC API 建立一个点对点连接,并传输视频流:
<!DOCTYPE html>
<html>
<head>
<title>WebRTC Example</title>
</head>
<body>
<h1>WebRTC Example</h1>
<video id="localVideo" autoplay></video>
<video id="remoteVideo" autoplay></video>
<button id="startButton">Start</button>
<script>
let localStream;
let peerConnection;
const configuration = { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] };
document.getElementById('startButton').addEventListener('click', async () => {
// 获取本地媒体流
localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
document.getElementById('localVideo').srcObject = localStream;
// 创建 RTCPeerConnection
peerConnection = new RTCPeerConnection(configuration);
// 添加本地流到 RTCPeerConnection
localStream.getTracks().forEach(track => peerConnection.addTrack(track, localStream));
// 处理远程流
peerConnection.ontrack = (event) => {
document.getElementById('remoteVideo').srcObject = event.streams[0];
};
// 创建和发送 offer
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
// 模拟信令服务器,直接设置远程描述
peerConnection.onicecandidate = (event) => {
if (event.candidate) {
// 发送 ICE 候选到远程对等方
}
};
// 模拟接收远程描述
const remoteDescription = new RTCSessionDescription(offer);
await peerConnection.setRemoteDescription(remoteDescription);
// 创建和发送 answer
const answer = await peerConnection.createAnswer();
await peerConnection.setLocalDescription(answer);
// 模拟接收 answer
await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
});
</script>
</body>
</html>
获取本地媒体流:
localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
document.getElementById('localVideo').srcObject = localStream;
使用 getUserMedia
获取本地视频和音频流,并将其显示在 <video>
元素中。
创建 RTCPeerConnection:
peerConnection = new RTCPeerConnection(configuration);
创建一个新的 RTCPeerConnection
实例,用于建立点对点连接。
添加本地流到 RTCPeerConnection:
localStream.getTracks().forEach(track => peerConnection.addTrack(track, localStream));
将本地媒体流的轨道添加到 RTCPeerConnection
中。
处理远程流:
peerConnection.ontrack = (event) => {
document.getElementById('remoteVideo').srcObject = event.streams[0];
};
当接收到远程流时,将其显示在另一个 <video>
元素中。
创建和发送 offer:
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
创建一个 SDP offer,并将其设置为本地描述。
模拟信令服务器:
getUserMedia
、RTCPeerConnection
和 RTCDataChannel
,这些 API 使得开发者可以在网页中实现实时音频、视频和数据通信。通过这些 API,开发者可以创建功能强大的实时通信应用,而无需依赖插件或第三方软件。
This will delete the page "主要的 WebRTC API和使用示例"
. Please be certain.