0Pricing
Real-Time Streaming Systems (WebRTC + Live Data) · Урок

Отображение удалённых аудио и видео

Реализуйте логику получения и отображения удалённых аудио- и видеопотоков от подключённых участников в приложении.

«Отображение удалённых аудио и видео» — бесплатный урок Real-Time Streaming Systems (WebRTC + Live Data) на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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 ontrack event is triggered on your RTCPeerConnection object.
  • 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 individual MediaStreamTrack (e.g., a single video track or audio track).
  • event.streams: An array of MediaStream objects. 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 MediaStream object to videoElement.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'), use document.createElement('audio').
  • Assign the MediaStream to audioElement.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 ontrack event fires for a new remote stream, create a new <video> or <audio> element.
  • Assign the incoming event.streams[0] to that new element's srcObject.
  • 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 ontrack event on RTCPeerConnection notifies you of incoming media.
  • You access the MediaStream via event.streams[0].
  • Assign this stream to an HTML <video> or <audio> element's srcObject property for display.
  • Remember essential attributes like autoplay and playsinline for smooth playback.

Now you can truly see and hear your connected peers!

Часто задаваемые вопросы

Урок «Отображение удалённых аудио и видео» бесплатный?

Да — полный текст урока «Отображение удалённых аудио и видео» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Real-Time Streaming Systems (WebRTC + Live Data), подпишись на CoddyKit PRO. Курс Real-Time Streaming Systems (WebRTC + Live Data) содержит 4 уроков всего.

Чему я научусь в уроке «Отображение удалённых аудио и видео»?

Реализуйте логику получения и отображения удалённых аудио- и видеопотоков от подключённых участников в приложении. Ты практикуешь Real-Time Streaming Systems (WebRTC + Live Data) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Real-Time Streaming Systems (WebRTC + Live Data)?

Предыдущий опыт не требуется. Real-Time Streaming Systems (WebRTC + Live Data) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 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)