การเพิ่มและนำแทร็กสื่อออก
เรียนรู้การจัดการแทร็กเสียงและวิดีโอภายใน `RTCPeerConnection` เพื่อให้สามารถปรับเปลี่ยนสตรีมแบบไดนามิกระหว่างการโทร
การเพิ่มและนำแทร็กสื่อออก เป็นบทเรียน Real-Time Streaming Systems (WebRTC + Live Data) ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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
kindproperty, either'audio'or'video'. - Enabled: The
enabledproperty (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:
- The
MediaStreamTrackyou want to send. - The
MediaStreamthe 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 = falseortrue. - 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 aMediaStreamTrack, returning anRTCRtpSender.removeTrack()stops sending a track by taking itsRTCRtpSender.- The remote peer listens for the
ontrackevent to receive new media. - You can mute/unmute using
track.enabledand switch sources by adding/removing tracks.
Mastering these methods allows for rich, interactive real-time experiences!
เรียนรู้ Real-Time Streaming Systems (WebRTC + Live Data) ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 12
- บทเรียน
- 48
คำถามที่พบบ่อย
บทเรียน “การเพิ่มและนำแทร็กสื่อออก” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การเพิ่มและนำแทร็กสื่อออก” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส 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 ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Real-Time Streaming Systems (WebRTC + Live Data) หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Real-Time Streaming Systems (WebRTC + Live Data) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การเพิ่มและนำแทร็กสื่อออก” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Real-Time Streaming Systems (WebRTC + Live Data) นี้ได้ไหม
ได้ บทเรียน Real-Time Streaming Systems (WebRTC + Live Data) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การเข้าถึงอุปกรณ์สื่อของผู้ใช้
- การเพิ่มและนำแทร็กสื่อออก
- การแสดงเสียงและวิดีโอจากระยะไกล
- การควบคุมคุณภาพสื่อและข้อจำกัด