用一个html页面实现2个rtc通道连接,用户A(rtc) 给 用户B(rtc2)发视频看,展示用户A的视频
效果:
权限请求
打通视频
控制台打印信息
全部代码:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video id="video"></video>
</body>
<script>
const err = (er) => {
console.log(er);
}
const getVideo = async () => {
const gumStream = await navigator.mediaDevices.getUserMedia(
{ video: true, audio: true });
for (const track of gumStream.getTracks()) {
rtc.addTrack(track, gumStream);
console.log(rtc, rtc.track)
}
rtc.createOffer((offer) => {
rtc.setLocalDescription(new RTCSessionDescription(offer), () => {
console.log('rtc setLocalDescription', rtc.signalingState);
creatertc2(offer);
}, err)
}, err)
// {
// offerToReceiveVideo: 1,
// }
// err后面可以加这个参数 也可以不加
// offerToReceiveVideo 可选 (Legacy) 传统的布尔选项,用于控制是否向远程对等方提供尝试发送视频的机会。如果此值为false
}
const rtc = new RTCPeerConnection();
getVideo()
let rtc2;
rtc.onicecandidate = (ice) => {
console.log('icecandidate')
if (rtc2 && ice.candidate) {
rtc2.addIceCandidate(new RTCIceCandidate(ice.candidate))
}
}
const creatertc2 = (offer) => {
rtc2 = new RTCPeerConnection();
rtc2.ontrack = (s) => {
console.log(s, 'ontrack2')
const video = document.getElementById('video');
video.srcObject = s.streams[0];
video.onloadedmetadata = () => {
video.play();
}
}
rtc2.onicecandidate = (ice) => {
console.log('icecandidate2')
if (rtc && ice.candidate) {
rtc.addIceCandidate(new RTCIceCandidate(ice.candidate))
}
}
rtc2.setRemoteDescription(new RTCSessionDescription(offer), () => {
console.log('rtc2 setRemoteDescription', rtc2.signalingState);
rtc2.createAnswer((answer) => {
rtc2.setLocalDescription(answer);
console.log('rtc2 setLocalDescription', rtc2.signalingState);
rtc.setRemoteDescription(answer);
console.log('rtc setRemoteDescription', rtc.signalingState);
}, err);
}, err)
}
</script>
</html>
注意事项:
- 顺序错了会不通:
-> 开始
-> new RTCPeerConnection(用户A)
-> addTrack(用户A)
-> createOffer(用户A)
-> setLocalDescription(用户A)
-> new RTCPeerConnection(用户B)
-> new RTCPeerConnection(用户B)
-> new RTCPeerConnection(用户B)
-> setRemoteDescription(用户B)
-> createAnswer(用户B)
-> setLocalDescription(用户B)
-> setRemoteDescription(用户A)
-> addIceCandidate(用户B, 用户A)
-> 完成 - 有的没有权限,或者被拒绝,我代码里没有考虑
- 视频播放使用onloadedmetadata事件触发一下
- addTrack 是新的写法(虽然现在不算新了,但是很多文章还保留这addstream,需要注意一下),
- 这里视频里出现的画面是rtc(用户A,addTrack)获取到的传递给rtc1(用户B,ontrack)
- ontrack 等监听事件小写!我就习惯驼峰了,找了半天问题
网友评论