如何使本地网络上的 WebRTC 视频流工作?
How to make WebRTC video streaming on local network working?
我正在尝试通过 WebRTC 在两个客户端之间建立对等连接,然后通过连接从摄像头流式传输视频。问题是,虽然我可以清楚地看到 remotePc.ontrack
事件被触发,但远程端没有显示视频。也没有抛出错误。我不想使用 icecandidates 机制(并且不需要),因为结果应用程序将仅在本地网络上使用(信令服务器只会为客户端交换 SDP)。为什么我的示例不起作用?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<video id="local" autoplay playsinline></video>
<video id="remote" autoplay playsinline></video>
<script>
const localVideoElem = document.getElementById("local");
const remoteVideoElem = document.getElementById("remote");
const localPc = new RTCPeerConnection();
const remotePc = new RTCPeerConnection();
remotePc.ontrack = (event) => {
remoteVideoElem.srcObject = event.streams[0];
};
navigator.mediaDevices
.getUserMedia({
video: true,
audio: false,
})
.then((stream) => {
localVideoElem.srcObject = stream;
stream
.getTracks()
.forEach((track) => localPc.addTrack(track, stream));
return localPc.createOffer({
offerToReceiveVideo: true,
offerToReceiveAudio: false,
});
})
.then((offer) => {
localPc.setLocalDescription(offer);
remotePc
.setRemoteDescription(offer)
.then(() => remotePc.createAnswer())
.then((answer) => {
remotePc.setLocalDescription(answer).then(() => {
localPc.setRemoteDescription(answer).then(() => {
console.log(localPc);
console.log(remotePc);
});
});
});
});
</script>
</body>
</html>
需要 ICE 候选人,因为他们会告诉您客户端将相互连接的本地地址。
虽然你不需要 STUN 服务器。
我正在尝试通过 WebRTC 在两个客户端之间建立对等连接,然后通过连接从摄像头流式传输视频。问题是,虽然我可以清楚地看到 remotePc.ontrack
事件被触发,但远程端没有显示视频。也没有抛出错误。我不想使用 icecandidates 机制(并且不需要),因为结果应用程序将仅在本地网络上使用(信令服务器只会为客户端交换 SDP)。为什么我的示例不起作用?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<video id="local" autoplay playsinline></video>
<video id="remote" autoplay playsinline></video>
<script>
const localVideoElem = document.getElementById("local");
const remoteVideoElem = document.getElementById("remote");
const localPc = new RTCPeerConnection();
const remotePc = new RTCPeerConnection();
remotePc.ontrack = (event) => {
remoteVideoElem.srcObject = event.streams[0];
};
navigator.mediaDevices
.getUserMedia({
video: true,
audio: false,
})
.then((stream) => {
localVideoElem.srcObject = stream;
stream
.getTracks()
.forEach((track) => localPc.addTrack(track, stream));
return localPc.createOffer({
offerToReceiveVideo: true,
offerToReceiveAudio: false,
});
})
.then((offer) => {
localPc.setLocalDescription(offer);
remotePc
.setRemoteDescription(offer)
.then(() => remotePc.createAnswer())
.then((answer) => {
remotePc.setLocalDescription(answer).then(() => {
localPc.setRemoteDescription(answer).then(() => {
console.log(localPc);
console.log(remotePc);
});
});
});
});
</script>
</body>
</html>
需要 ICE 候选人,因为他们会告诉您客户端将相互连接的本地地址。
虽然你不需要 STUN 服务器。