0Pricing
Real-Time Streaming Systems (WebRTC + Live Data) · 강의

미디어 트랙 추가 및 제거

`RTCPeerConnection` 내에서 오디오 및 비디오 트랙을 관리하여 통화 중 스트림을 동적으로 조작하는 방법을 배웁니다.

미디어 트랙 추가 및 제거은(는) CoddyKit의 무료 Real-Time Streaming Systems (WebRTC + Live Data) 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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!

자주 묻는 질문

“미디어 트랙 추가 및 제거” 강의는 무료인가요?

네 — “미디어 트랙 추가 및 제거” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Real-Time Streaming Systems (WebRTC + Live Data) 강의 전체를 잠금 해제할 수 있습니다. Real-Time Streaming Systems (WebRTC + Live Data) 강의에는 총 4개의 강의가 포함되어 있습니다.

“미디어 트랙 추가 및 제거”에서 뭘 배우나요?

`RTCPeerConnection` 내에서 오디오 및 비디오 트랙을 관리하여 통화 중 스트림을 동적으로 조작하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Real-Time Streaming Systems (WebRTC + Live Data)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Real-Time Streaming Systems (WebRTC + Live Data)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Real-Time Streaming Systems (WebRTC + Live Data)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“미디어 트랙 추가 및 제거” 강의는 얼마나 걸리나요?

대부분의 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)(으)로 돌아가기