我有一个已定义RTCPeerConnectionontrack实例:

 newConnection.ontrack = receivedStream // remote

SDP交换完成后,对等方将添加其本地流:
 connection.addStream(stream); // local

我看到receivedStream每个流被调用两次-检查e.track向我展示了第一次调用是针对audio轨道,第二次是video轨道。

奇怪的是,检查e.streams[0]并在其上调用getTracks会给我两个MediaStreamTracks-一个用于音频,另一个用于视频:

javascript - RTC对等连接-两次接收流-LMLPHP

因此,尽管调用了MediaStreamTracks,但我在receivedStream的两个调用之间划分了四个 addStream
receivedStream在这里:
 function receivedStream(e) {
        var stream = e.streams[0]; // this gets invoked twice when adding one stream!
        if (!stream) {
            throw new Error("no stream found");
        };
        // this gets me the corresponding connection
        waitForStream(stream.id).then(function (connection) {
            // get element
            targetVideoElement[0].srcObject = stream; // this now gets called twice per stream - once for audio, once for video
        }).catch(function (error) {
           // log
        });
    }

最佳答案

您可以对每个MediaStreamTrack执行相同的过程,即将MediaStreamTrack添加到MediaStream实例,然后将.srcObject设置为HTMLMediaElement

const mediaStream = new MediaStream();

const video = document.querySelector("video");

for (const track of receivedMediaStream) {
  mediaStream.addTrack(track)
}

video.srcObject = mediaStream;

09-20 08:42