Exibição de áudio e vídeo remotos
Implemente a lógica para receber e exibir fluxos de áudio e vídeo remotos de pares conectados em sua aplicação.
Exibição de áudio e vídeo remotos é uma aula grátis de Real-Time Streaming Systems (WebRTC + Live Data) no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Real-Time Streaming Systems (WebRTC + Live Data), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Real-Time Streaming Systems (WebRTC + Live Data) inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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!
Perguntas Frequentes
A aula “Exibição de áudio e vídeo remotos” é grátis?
Sim — o texto completo de “Exibição de áudio e vídeo remotos” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Real-Time Streaming Systems (WebRTC + Live Data), atualize para CoddyKit PRO. O curso de Real-Time Streaming Systems (WebRTC + Live Data) inclui 4 aulas no total.
O que vou aprender em “Exibição de áudio e vídeo remotos”?
Implemente a lógica para receber e exibir fluxos de áudio e vídeo remotos de pares conectados em sua aplicação. Você pratica Real-Time Streaming Systems (WebRTC + Live Data) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Real-Time Streaming Systems (WebRTC + Live Data)?
Nenhuma experiência prévia é necessária. Real-Time Streaming Systems (WebRTC + Live Data) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Exibição de áudio e vídeo remotos”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Real-Time Streaming Systems (WebRTC + Live Data)?
Sim. Cada aula de Real-Time Streaming Systems (WebRTC + Live Data) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Acesso aos dispositivos de mídia do usuário
- Adição e remoção de faixas de mídia
- Exibição de áudio e vídeo remotos
- Controle de Qualidade e Restrições de Mídia