0Pricing
Real-Time Streaming Systems (WebRTC + Live Data) · 课时

添加和移除媒体轨道

学习如何管理 `RTCPeerConnection` 中的音频和视频轨道,从而在通话过程中动态处理媒体流。

添加和移除媒体轨道 是 CoddyKit 上的免费 Real-Time Streaming Systems (WebRTC + Live Data) 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Real-Time Streaming Systems (WebRTC + Live Data) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Real-Time Streaming Systems (WebRTC + Live Data) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Dynamic Media in WebRTC Calls

Imagine you're in a video call and want to mute your microphone or switch your camera. How does WebRTC handle these changes without dropping the call?

This lesson explores how to dynamically add and remove audio/video tracks from an active WebRTC peer connection. This is crucial for creating interactive and flexible real-time applications.

What is a MediaStreamTrack?

Before managing tracks, let's clarify what they are. A MediaStreamTrack represents a single audio or video component within a MediaStream.

  • Kind: Tracks have a kind property, either 'audio' or 'video'.
  • Enabled: The enabled property (boolean) lets you temporarily pause/unpause a track without removing it.

Sending Media with addTrack()

To start sending a local audio or video track to a remote peer, you use the RTCPeerConnection.addTrack() method.

It takes two arguments:

  1. The MediaStreamTrack you want to send.
  2. The MediaStream the track belongs to (important for grouping related tracks).

This method tells the peer connection to prepare and send this track's data.

Code: Adding a Local Video Track

Let's see how you'd add a local video track to your RTCPeerConnection. This snippet sets up a basic peer connection and adds a camera feed.

async function addLocalVideoTrack() {
  // In a real app, 'pc' would be an already established RTCPeerConnection
  const pc = new RTCPeerConnection();

  try {
    // Get access to the user's camera
    const localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
    const videoTrack = localStream.getVideoTracks()[0];

    // Add the video track to the peer connection
    const sender = pc.addTrack(videoTrack, localStream);
    console.log('Video track added! RTCRtpSender:', sender);

    // In a full WebRTC app, you'd now create an offer and exchange SDP
    // pc.createOffer().then(offer => pc.setLocalDescription(offer)).then(() => sendOfferToRemote(pc.localDescription));

  } catch (error) {
    console.error('Error adding video track:', error);
  }
}

addLocalVideoTrack();

Understanding RTCRtpSender

When you call pc.addTrack(), it returns an RTCRtpSender object. This object is your handle to manage the sending of that specific track.

  • It allows you to modify parameters related to how the track is sent.
  • It's also required if you later want to remove the track from the peer connection.

Stopping Media with removeTrack()

To stop sending a particular media track, you use the RTCPeerConnection.removeTrack() method.

This method takes one argument: the RTCRtpSender object that was returned when you originally called addTrack() for that track.

Once removed, the track's data will no longer be transmitted over the peer connection.

Code: Implementing removeTrack()

Let's extend our previous example to demonstrate how to remove a track after it has been added. We need to keep track of the RTCRtpSender.

let peerConnection; // Global or accessible RTCPeerConnection instance
let videoSender;    // Global or accessible RTCRtpSender instance
let localVideoTrack; // Global or accessible MediaStreamTrack

async function setupAndAddTrack() {
  peerConnection = new RTCPeerConnection();

  try {
    const localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
    localVideoTrack = localStream.getVideoTracks()[0];
    videoSender = peerConnection.addTrack(localVideoTrack, localStream);
    console.log('Video track added. Sender:', videoSender);
  } catch (error) {
    console.error('Error during setup or addTrack:', error);
  }
}

function removeLocalVideoTrack() {
  if (peerConnection && videoSender) {
    peerConnection.removeTrack(videoSender);
    localVideoTrack.stop(); // Stops the camera/mic itself
    console.log('Video track removed and stopped!');
  } else {
    console.log('No track to remove or not set up.');
  }
}

// Simulate adding a track, then removing it after 3 seconds
setupAndAddTrack().then(() => {
  setTimeout(removeLocalVideoTrack, 3000);
});

Receiving Remote Track Updates

On the receiving end, how does a peer know that a new track has been added or an existing one removed by the sender?

The RTCPeerConnection.ontrack event listener is fired on the receiving peer when a new MediaStreamTrack is added to the remote description. This is where you would typically attach the incoming track to a video or audio element.

Real-World Track Management

Dynamic track management is essential for many real-time features:

  • Muting/Unmuting: Simply toggle track.enabled = false or true.
  • Camera/Mic Switching: Remove the old track, get a new one from getUserMedia(), and add the new track.
  • Screen Sharing: Get a screen share track (e.g., with getDisplayMedia()) and add it to the peer connection.

Test Your Track Knowledge

RTCPeerConnection allows for dynamic management of media streams. Let's check your understanding of how tracks are handled.

Recap: Dynamic Media Control

In this lesson, you learned how to dynamically manage media tracks within a WebRTC call:

  • addTrack() sends a MediaStreamTrack, returning an RTCRtpSender.
  • removeTrack() stops sending a track by taking its RTCRtpSender.
  • The remote peer listens for the ontrack event to receive new media.
  • You can mute/unmute using track.enabled and switch sources by adding/removing tracks.

Mastering these methods allows for rich, interactive real-time experiences!

常见问题解答

「添加和移除媒体轨道」课时是免费的吗?

是的 — 「添加和移除媒体轨道」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Real-Time Streaming Systems (WebRTC + Live Data) 课程的其余内容,请升级到 CoddyKit PRO。 Real-Time Streaming Systems (WebRTC + Live Data) 课程共包含 4 节课。

「添加和移除媒体轨道」这节课中我会学到什么?

学习如何管理 `RTCPeerConnection` 中的音频和视频轨道,从而在通话过程中动态处理媒体流。 你通过在浏览器中直接运行的动手代码来练习 Real-Time Streaming Systems (WebRTC + Live Data),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Real-Time Streaming Systems (WebRTC + Live Data) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Real-Time Streaming Systems (WebRTC + Live Data) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「添加和移除媒体轨道」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Real-Time Streaming Systems (WebRTC + Live Data) 课中编写并运行代码吗?

能。每节 Real-Time Streaming Systems (WebRTC + Live Data) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 访问用户媒体设备
  2. 添加和移除媒体轨道
  3. 显示远程音频和视频
  4. 媒体质量与约束控制
← 返回 Real-Time Streaming Systems (WebRTC + Live Data)