写一个webrtc demo
时间: 2023-08-24 17:09:50 浏览: 250
很抱歉,我作为一个AI语言模型,并没有能力编写和展示实时的WebRTC demo。但我可以提供一些基本的代码来启动一个简单的WebRTC连接。
1. 首先,需要创建两个HTML文件:index.html和remote.html。index.html是发送方,remote.html是接收方。
2. 在index.html中,需要创建一个video标签和两个button标签,一个用于开始连接,另一个用于断开连接。
```html
<video id="localVideo"></video>
<button id="startButton">Start Connection</button>
<button id="stopButton">Stop Connection</button>
```
3. 在remote.html中,需要创建一个video标签来显示接收到的视频流。
```html
<video id="remoteVideo"></video>
```
4. 在JavaScript中,需要使用WebRTC API来建立连接。首先,需要创建一个RTCPeerConnection对象。
```javascript
const localVideo = document.querySelector('#localVideo');
const remoteVideo = document.querySelector('#remoteVideo');
const startButton = document.querySelector('#startButton');
const stopButton = document.querySelector('#stopButton');
let localStream;
let pc1;
let pc2;
const offerOptions = {
offerToReceiveVideo: 1,
};
startButton.addEventListener('click', start);
stopButton.addEventListener('click', stop);
async function start() {
try {
localStream = await navigator.mediaDevices.getUserMedia({ video: true });
localVideo.srcObject = localStream;
} catch (e) {
console.error('getUserMedia() error:', e);
return;
}
pc1 = new RTCPeerConnection();
pc2 = new RTCPeerConnection();
pc1.addEventListener('icecandidate', e => onIceCandidate(pc1, pc2, e));
pc2.addEventListener('icecandidate', e => onIceCandidate(pc2, pc1, e));
pc2.addEventListener('track', gotRemoteStream);
localStream.getTracks().forEach(track => pc1.addTrack(track, localStream));
try {
const offer = await pc1.createOffer(offerOptions);
await onCreateOfferSuccess(offer, pc1, pc2);
} catch (e) {
onCreateSessionDescriptionError(e);
}
}
function onCreateSessionDescriptionError(error) {
console.error(`Failed to create session description: ${error.toString()}`);
}
async function onCreateOfferSuccess(desc, pc1, pc2) {
console.log(`Offer from pc1\n${desc.sdp}`);
await pc1.setLocalDescription(desc);
await pc2.setRemoteDescription(desc);
try {
const answer = await pc2.createAnswer();
await onCreateAnswerSuccess(answer, pc1, pc2);
} catch (e) {
onCreateSessionDescriptionError(e);
}
}
async function onCreateAnswerSuccess(desc, pc1, pc2) {
console.log(`Answer from pc2:\n${desc.sdp}`);
await pc2.setLocalDescription(desc);
await pc1.setRemoteDescription(desc);
}
function onIceCandidate(pc, otherPc, event) {
if (event.candidate) {
otherPc.addIceCandidate(event.candidate)
.then(() => {
console.log('addIceCandidate success');
}).catch((err) => {
console.error(`addIceCandidate error: ${err}`);
});
}
}
function gotRemoteStream(e) {
if (remoteVideo.srcObject !== e.streams[0]) {
remoteVideo.srcObject = e.streams[0];
console.log('received remote stream');
}
}
function stop() {
pc1.close();
pc2.close();
pc1 = null;
pc2 = null;
startButton.disabled = false;
stopButton.disabled = true;
}
```
5. 最后,在本地运行index.html和remote.html文件,点击“Start Connection”按钮,即可建立WebRTC连接并开始传输视频流。
以上只是一个简单的WebRTC连接示例,实际中可能需要更多的代码和调试。同时,需要注意WebRTC连接需要在HTTPS环境下运行,否则可能会出现安全问题。
阅读全文