首页 > 解决方案 > 未捕获的类型错误:无法读取 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”这个错误

你能给我任何想法吗?

谢谢你

标签: javascriptwebrtc

解决方案


由于流是由 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));
});

推荐阅读