javascript - 未捕获的类型错误:无法读取 null 的属性“getTracks”
问题描述
我一直在尝试将 webRTC 广播源更改为多对一
我认为一对多(广播)和多对一略有不同[在此处输入图像描述][1] [1]:https://i.stack.imgur.com/zAzbt.png
他们有 peerConnections,一切都很好。
调用者将 MediaStream 发送给所有被调用者。
所以我认为
让我们从 caller 到 callee 获取信号,并将 MediaStream 从 Callee 带到 Caller。
所以我把这段代码放到被调用方
被调用者.js
socket.on('offer', (id, description) => {
peerConnection = new RTCPeerConnection(config);
navigator.mediaDevices
.getUserMedia(constraints)
.then((stream) => {
video.srcObject = stream;
})
.catch((error) => console.error(error));
let stream = video.srcObject;
stream
.getTracks()
.forEach((track) => peerConnection.addTrack(track, stream));
peerConnection
.setRemoteDescription(description)
.then(() => peerConnection.createAnswer())
.then((sdp) => peerConnection.setLocalDescription(sdp))
.then(() => {
socket.emit('answer', id, peerConnection.localDescription);
});
peerConnection.onicecandidate = (event) => {
if (event.candidate) {
socket.emit('candidate', id, event.candidate);
}
};
});
调用者.js
socket.on('answer', (id, description) => {
peerConnections[id].setRemoteDescription(description);
peerConnections.ontrack = (event) => {
video.srcObject = event.streams[0];
};
});
我从 callee.js 得到“未捕获的类型错误:无法读取属性 'getTracks' of null”这个错误
你能给我任何想法吗?
谢谢你
解决方案
由于流是由 Promise 获取的,所以 getTracks() 会在 getUserMedia() 之前执行。所以,修改它,让它在 Promise 之后执行。
exp:未测试
socket.on("offer", (id, description) => {
peerConnection = new RTCPeerConnection(config);
peerConnection.onicecandidate = event => {
if (event.candidate) {
socket.emit("candidate", id, event.candidate);
}
};
navigator.mediaDevices
.getUserMedia(constraints)
.then(stream => {
video.srcObject = stream;
stream.getTracks().forEach(track => peerConnection.addTrack(track, stream));
})
.then(peerConnection.setRemoteDescription(description))
.then(() => peerConnection.createAnswer())
.then(sdp => peerConnection.setLocalDescription(sdp))
.then(() => {
socket.emit("answer", id, peerConnection.localDescription);
})
.catch(error => console.error(error));
});
推荐阅读
- java - 表中键数的准确范围
- javascript - js中的两个for循环。无法在嵌套的 for 循环上工作
- javascript - Angular 2:滚动动画
- guidewire - 如何在 Guidewire 中安装 DCEVM?
- r - 移动 geom_label 的框,使它们不重叠
- elasticsearch - 在 Elasticsearch 中更改设置的最佳解决方案
- javascript - 正则表达式不允许没有前缀或后缀的特殊字符
- reactjs - 为什么 React-Scroll activeClass 不起作用?
- python - 如何删除隐藏的 utdated scipy 文件,使其不会在 VS Code OSX 中使用 python 导入
- mysql - Mysql 语句有语法问题