peerjs icon indicating copy to clipboard operation
peerjs copied to clipboard

How to addTracks to a connection?

Open ohuu opened this issue 3 years ago • 5 comments

I'm trying to stream multiple video and audio streams from one peer to the other over a single connection. From what I can gather reading WebRTC docs this can be acheived by called RtcPeerConnection.addTrack on one side of the connection as long as the other side has a track listener (e.g. pc.addEventListener('track', (evt) => ...)).

However, this doesn't seem to work. My code is as follows:

Caller:

const call = peer.call(peerId, localStream);

call.on("stream", (remoteStream) => { // <-- triggered when call is answered
    console.log(`received remote stream from host ${remoteSocketId} ${remoteStream}`);
    addUpdateStream(remoteSocketId, remoteStream);
});

// listen for tracks
console.log("adding track event listener");
call.peerConnection.addEventListener("track", (evt) => { // <-- Not triggered
    console.log(`received track ${evt.track.label} with ${evt.streams.length} streams from the host`);
    evt.streams.forEach(stream => {
        console.log(`${stream.id} - ${stream.getTracks().length}`);
    })
});

Receiver:

peer.on("call", (call) => {
    call.answer(localStream); // Answer the call with an A/V stream.
    call.on("stream", (remoteStream) => {
        addUpdateStream(remoteSocketId, remoteStream);
    });

    // if you are the host then add the studio streams as tracks to the local stream
    if (amiHost.value) {
        hostStreams.value.forEach(stream => {
            stream.getTracks().forEach(track => {
                console.log(`adding track ${track.label} to peer connection`);
                call.peerConnection.addTrack(track, stream); // <-- tracks are definitely added to the connection
            })
        });
    }
});

Am I misunderstanding something here? Is it even possible to add multiple streams to a single connection or do I need to open a new connection for each stream? If there are any examples of doing something similar that would be great.

ohuu avatar Mar 08 '21 17:03 ohuu

Did you happen to figure out a solution for this?

bobby-white avatar Dec 16 '21 20:12 bobby-white

same problem

doleron avatar Apr 25 '22 11:04 doleron

same problem

skytree8 avatar May 08 '23 09:05 skytree8

up please ;)

aschelch avatar Dec 10 '23 13:12 aschelch

please help

qstiegler avatar Feb 08 '24 09:02 qstiegler