Once a RTCPeerConnection
is connected to a remote peer, it is possible to
stream audio and video between them. This is the point where we connect the
stream we receive from getUserMedia()
to the RTCPeerConnection
. A media
stream consists of at least one media track, and these are individually added
to the RTCPeerConnection
when we want to transmit the media to the remote
peer.
const localStream = await getUserMedia({vide: true, audio: true});
const peerConnection = new RTCPeerConnection(iceConfig);
localStream.getTracks().forEach(track => {
peerConnection.addTrack(track, localStream);
});
Tracks can be added to a RTCPeerConnection
before it has connected to a remote
peer, so it makes sense to perform this setup as early as possible instead of
waiting for the connection to be completed.
添加远程轨道
To receive the remote tracks that were added by the other peer, we register a
listener on the local RTCPeerConnection
listening for the track
event. The
RTCTrackEvent
contains an array of MediaStream
objects that have the same
MediaStream.id
values as the peer's corresponding local streams. In our
example, each track is only associated with a single stream.
Note that while MediaStream
IDs match on both sides of the peer connection,
the same is generally not true for MediaStreamTrack
IDs.
const remoteVideo = document.querySelector('#remoteVideo');
peerConnection.addEventListener('track', async (event) => {
const [remoteStream] = event.streams;
remoteVideo.srcObject = remoteStream;
});