大网数据广告活动
Web 标准与前端开发

RTCRtpSender: replaceTrack() method

· 52CE 我爱测

The RTCRtpSender method **`replaceTrack()`** replaces the track currently being used as the sender's source with a new MediaStreamTrack.

WebRTC

The RTCRtpSender method replaceTrack() replaces the track currently being used as the sender's source with a new MediaStreamTrack.

The new track must be of the same media kind (audio, video, etc.) and switching the track should not require negotiation.

Among the use cases for replaceTrack() is the common need to switch between the rear- and front-facing cameras on a phone. With replaceTrack(), you can have a track object for each camera and switch between the two as needed. See the example switching video cameras below.

Syntax

replaceTrack(newTrack)

Parameters

  • newTrack
    • : A MediaStreamTrack specifying the track with which to replace the RTCRtpSender's current source track. The new track's MediaStreamTrack.kind must be the same as the current track's, or the replace track request will fail.

Return value

A Promise which is fulfilled once the track has been successfully replaced. The promise is rejected if the track cannot be replaced for any reason; this is commonly because the change would require renegotiation of the codec, which is not allowed (see Things that require negotiation).

If newTrack was omitted or was null, replaceTrack() stops the sender. No negotiation is required in this case.

When the promise is fulfilled, the fulfillment handler receives a value of undefined.

Exceptions

If the returned promise is rejected, one of the following exceptions is provided to the rejection handler:

  • InvalidModificationError DOMException
    • : Returned if replacing the RTCRtpSender's current track with the new one would require negotiation.
  • InvalidStateError DOMException
    • : Returned if the track on which this method was called is stopped rather than running.
  • TypeError
    • : Returned if the new track's kind doesn't match the original track.

Usage notes

Things that require negotiation

Most track replacements can be done without renegotiation. In fact, even changes that seem huge can be done without requiring negotiation. However, some changes may require negotiation and thus fail replaceTrack():

  • The new track has a resolution which is outside the bounds of the dimensions negotiated with the peer; however, most browser end points allow resolution changes.
  • The new track's frame rate is high enough to cause the codec's block rate to be exceeded.
  • The new track is a video track and its raw or pre-encoded state differs from that of the original track.
  • The new track is an audio track with a different number of channels from the original.
  • Media sources that have built-in encoders — such as hardware encoders — may not be able to provide the negotiated codec. Software sources may not implement the negotiated codec.

Examples

Switching video cameras

const localConnection = new RTCPeerConnection();
const remoteConnection = new RTCPeerConnection();
// Configuring these to use the WebRTC API can be explored at
// https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample
const connections = [localConnection, remoteConnection];
function setCamera(selectedCamera) {
  navigator.mediaDevices
    .getUserMedia({
      video: {
        deviceId: {
          exact: selectedCamera,
        },
      },
    })
    .then((stream) => {
      const [videoTrack] = stream.getVideoTracks();
      connections.forEach((pc) => {
        const sender = pc
          .getSenders()
          .find((s) => s.track.kind === videoTrack.kind);
        console.log("Found sender:", sender);
        sender.replaceTrack(videoTrack);
      });
    })
    .catch((err) => {
      console.error(`Error happened: ${err}`);
    });
}

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。