RTCTrackEvent
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
TheWebRTC API interfaceRTCTrackEvent
represents thetrack
event, which is sent when a newMediaStreamTrack
is added to anRTCRtpReceiver
which is part of theRTCPeerConnection
.
The target is theRTCPeerConnection
object to which the track is being added.
This event is sent by the WebRTC layer to the website or application, so you will not typically need to instantiate anRTCTrackEvent
yourself.
Constructor
RTCTrackEvent()
Creates and returns a new
RTCTrackEvent
object. You will probably not need to create new track events yourself, since they're typically created by the WebRTC infrastructure and sent to the connection'sontrack
event handler.
Instance properties
SinceRTCTrackEvent
is based onEvent
, its properties are also available.
receiver
Read onlyThe
RTCRtpReceiver
used by the track that's been added to theRTCPeerConnection
.streams
Read onlyOptionalAn array of
MediaStream
objects, each representing one of the media streams to which the addedtrack
belongs. By default, the array is empty, indicating a streamless track.track
Read onlyThe
MediaStreamTrack
which has been added to the connection.transceiver
Read onlyThe
RTCRtpTransceiver
being used by the new track.
Track event types
There is only one type of track event.
track
Thetrack
event is sent to theRTCPeerConnection
when a new track has been added to the connection. By the time thetrack
event is delivered to theRTCPeerConnection
'sontrack
handler, the new media has completed its negotiation for a specificRTCRtpReceiver
(which is specified by the event'sreceiver
property).
In addition, theMediaStreamTrack
specified by the receiver'strack
is the same one specified by the event'strack
, and the track has been added to any associated remoteMediaStream
objects.
You can add atrack
event listener to be notified when the new track is available so that you can, for example, attach its media to a<video>
element, using eitherRTCPeerConnection.addEventListener()
or theontrack
event handler property.
Note:It may be helpful to keep in mind that you receive thetrack
event when a new inbound track has been added to your connection, and you calladdTrack()
to add a track to the far end of the connection, thereby triggering atrack
event on the remote peer.
Example
This simple example creates an event listener for thetrack
event which sets thesrcObject
of the<video>
element with the IDvideo-box
to the first stream in the list passed in the event'sstreams
array.
peerConnection.addEventListener( "track", (e) => { let videoElement = document.getElementById("video-box"); videoElement.srcObject = e.streams[0]; }, false,);
Specifications
Specification |
---|
WebRTC: Real-Time Communication in Browsers # dom-rtctrackevent |