Sweshi's Tutorials

Beginner Friendly WEB RTC Tutorial

Event Handlers, Methods and Properties of the MediaStream API


The MediaStream API in WebRTC provides a way to access and manipulate streams of audio and video data. Most online streaming applications that you probably use have the ability to enable or disable video or audio. This can be achieved by manipulating the MediaStream API. MediaStream objects represent streams of media content, and they are commonly used in the context of real-time communication applications such as video conferencing. Here are some key properties, methods, and event handlers associated with the MediaStream API that will be used later in this tutorial:



MediaStream Properties

  1. MediaStream.id
    • Description: Represents a unique identifier for the stream.
    • Type: DOMString.
  2. MediaStream.active
    • Description: Indicates whether the stream is currently active.
    • Type: Boolean.
  3. MediaStream.onaddtrack
    • Description: An event handler that is called when a new track is added to the stream.
    • Type: EventHandler.
  4. Mediastream.onremovetrack
    • Description: An event handler that is called when a track is removed from the stream.
    • Type: EventHandler.

MediaStream Methods

  1. MediaStream.getAudioTracks()
    • Description: Returns an array of all audio tracks in the stream.
    • Return Type: Array of MediaStreamTrack.
  2. MediaStream.getVideoTracks()
    • Description: Returns an array of all video tracks in the stream.
    • Return Type: Array of MediaStreamTrack.
  3. MediaStream.getTracks()
    • Description: Returns an array of all tracks (both audio and video) in the stream.
    • Return Type: Array of MediaStreamTrack.
  4. Mediastream.getTrackById(trackid)
    • Description: Returns the track with the specified ID.
    • Parameters: `trackId` (DOMString) - The ID of the track to retrieve.
    • Return Type: MediaStreamTrack or null if not found.
  5. MediaStream.addTrack(track)
    • Description: Adds a new track to the stream.
    • Parameters: `track` (MediaStreamTrack) - The track to add.
  6. MediaStream.removeTrack(track)
    • Description: Removes the specified track from the stream.
    • Parameters: `track` (MediaStreamTrack) - The track to remove.

MediaStream Event Handlers

  1. MediaStream.onactive
    • Description: An event handler that is called when the stream becomes active.
  2. MediaStream.oninactive
    • Description: An event handler that is called when the stream becomes inactive.
  3. MediaStream.onended
    • Description: An event handler that is called when the stream ends (no more tracks).

These properties, methods, and event handlers allow developers to interact with and manage media streams in WebRTC applications. They provide the necessary tools to work with audio and video tracks, add or remove tracks dynamically, and respond to changes in the stream's state.