显示远程音频和视频
在应用中实现接收并显示已连接对等端的远程音频和视频流的逻辑。
显示远程音频和视频 是 CoddyKit 上的免费 Real-Time Streaming Systems (WebRTC + Live Data) 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Real-Time Streaming Systems (WebRTC + Live Data) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Real-Time Streaming Systems (WebRTC + Live Data) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
See and Hear Others
WebRTC enables direct communication, but how do we actually see and hear what a remote peer is sending?
- We'll learn how to capture incoming audio/video data.
- Then, how to display this data in your web application using standard HTML elements.
- This is crucial for building video calls, live streaming, and more!
The 'ontrack' Event
When a remote peer sends a media stream, your RTCPeerConnection needs to know about it. This is handled by the ontrack event.
- The
ontrackevent is triggered on yourRTCPeerConnectionobject. - It fires when a new
MediaStreamTrack(like an audio or video track) is received from the remote peer. - This event is your gateway to accessing the remote media.
Accessing Remote Streams
The ontrack event provides an event object (let's call it event) that contains important information:
event.track: The individualMediaStreamTrack(e.g., a single video track or audio track).event.streams: An array ofMediaStreamobjects. Typically, the first item (event.streams[0]) contains the full remote stream with all its tracks.
We usually work with event.streams[0] to get the complete stream for display.
Display with 'srcObject'
Once you have the MediaStream from the remote peer, how do you show it?
HTML5 <video> and <audio> elements have a special property called srcObject.
- You can directly assign a
MediaStreamobject tovideoElement.srcObject. - This property tells the media element to play the stream without needing to create a temporary URL.
- It's the modern and preferred way to display streams.
Dynamic Media Elements
For WebRTC, you often don't have a fixed number of video elements. You'll create them on the fly as peers connect:
Use document.createElement() to create new <video> or <audio> tags.
const videoElement = document.createElement('video');
// ... set attributes and append to DOM ...These elements can then be styled and added to your page layout.
Code: Attach a Stream to Video
This example shows how to get a local camera stream and attach it to a dynamically created video element using srcObject. This is exactly how you'd attach a remote stream after receiving it via ontrack!
const videoContainer = document.getElementById('videos') || document.body;
function displayStream(stream) {
const video = document.createElement('video');
video.autoplay = true;
video.playsinline = true;
video.width = 300;
video.height = 200;
video.style.border = '2px solid blue';
video.style.margin = '5px';
videoContainer.appendChild(video);
video.srcObject = stream; // Attach the stream
console.log('Stream attached to video element.');
}
// Simulate getting a stream (e.g., from getUserMedia or ontrack)
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(localStream => {
console.log('Got local stream. Displaying...');
displayStream(localStream);
})
.catch(e => {
console.error('Error getting stream:', e);
const errorMessage = document.createElement('p');
errorMessage.innerText = 'Error: ' + e.message + '. Make sure camera is allowed.';
videoContainer.appendChild(errorMessage);
});Handling Audio-Only Streams
The process for displaying remote audio-only streams is very similar:
- Instead of
document.createElement('video'), usedocument.createElement('audio'). - Assign the
MediaStreamtoaudioElement.srcObject. - Audio elements are typically invisible, so no need for width/height styling.
The browser will play the audio in the background once the stream is attached.
Multiple Peers, Multiple Streams
In a multi-party call, you'll receive streams from several remote peers. Each peer's stream needs its own display:
- Every time an
ontrackevent fires for a new remote stream, create a new<video>or<audio>element. - Assign the incoming
event.streams[0]to that new element'ssrcObject. - You might use a unique ID for each peer to manage their respective media elements.
Essential Media Attributes
When creating media elements for WebRTC, some attributes are vital:
autoplay: Ensures the media starts playing automatically.playsinline: Crucial for iOS devices to play video directly within the browser, not fullscreen.muted: Often used for your local video preview to prevent echo, but usually unmuted for remote videos.controls: (Optional) Displays browser's default play/pause, volume controls.
Quick Check: Displaying Streams
You've successfully received a MediaStream from a remote peer. Which HTML property should you use to display this stream in a <video> element?
Recap: See & Hear
Great job! You've learned how to bring remote audio and video into your WebRTC application:
- The
ontrackevent onRTCPeerConnectionnotifies you of incoming media. - You access the
MediaStreamviaevent.streams[0]. - Assign this stream to an HTML
<video>or<audio>element'ssrcObjectproperty for display. - Remember essential attributes like
autoplayandplaysinlinefor smooth playback.
Now you can truly see and hear your connected peers!
用 AI 导师学习 Real-Time Streaming Systems (WebRTC + Live Data) — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「显示远程音频和视频」课时是免费的吗?
是的 — 「显示远程音频和视频」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Real-Time Streaming Systems (WebRTC + Live Data) 课程的其余内容,请升级到 CoddyKit PRO。 Real-Time Streaming Systems (WebRTC + Live Data) 课程共包含 4 节课。
「显示远程音频和视频」这节课中我会学到什么?
在应用中实现接收并显示已连接对等端的远程音频和视频流的逻辑。 你通过在浏览器中直接运行的动手代码来练习 Real-Time Streaming Systems (WebRTC + Live Data),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Real-Time Streaming Systems (WebRTC + Live Data) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Real-Time Streaming Systems (WebRTC + Live Data) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「显示远程音频和视频」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Real-Time Streaming Systems (WebRTC + Live Data) 课中编写并运行代码吗?
能。每节 Real-Time Streaming Systems (WebRTC + Live Data) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。