Skip to main content

Stream media to a channel

Users often need to play video and audio files during online social and business interactions. Video SDK enables you to add media playing functionality to your app. This page shows you how to use the media player classes in Video SDK to enable your users to publish media files to a channel.

Understand the tech

When a user selects a media file to play, you open the media file using a media player instance. When the file is ready to be played, you setup the local video container to display the media player output. You update the channel media options to start publishing the media player stream, then stop publishing the camera and microphone streams. The remote user sees the camera and microphone streams of the media publishing user replaced by media streams.

The following figure shows the workflow you need to integrate media player functionality into your app.

play media

Prerequisites

In order to follow this procedure you must have:

  • Implemented the SDK quickstart project for Interactive Live Streaming.
  • Physical media input devices, such as a camera and a microphone.
  • A JavaScript package manager such as npm.
  • An Agora account and project.

  • A computer with Internet access.

    Ensure that no firewall is blocking your network communication.

Project setup

To create the environment necessary to implement playing media files into your app, open the SDK quickstart Interactive Live Streaming project you created previously.

Add a media player to your app

This section shows how to use the Video SDK to implement a media player into your app, step-by-step.

Implement the user interface

In a real-word application, you provide several buttons to enable a user to open, play, pause and stop playing files in the media player. In this page, you use a single Button to demonstrate the basic media player functions. You also add two div to display the play progress to the user. To implement this UI, in index.html, add the following code after <button type="button" id="leave">Leave</button>:

<button type="button" id="mediaPlayer">Open Media File</button>
<div style="width: 400px; height: 10px; background-color: lightgray; padding: 2px;">
<div id ="bar" style ="width: 0; height: 100%; background-color: rgb(172, 50, 70); transition: width 0.2s;"></div>
</div>
Copy

Handle the system logic

To setup your project to use the media player APIs, take the following steps:

  1. Add the required imports

    To import the required Agora libraries, in preload.js, add the following before createAgoraRtcEngine, statement:

    MediaPlayerState,
    ChannelMediaOptions,
    Copy
  2. Declare the variables you need

    To create and manage an instance of the media player and access the UI elements, in preload.js, add the following to the list of declarations:

    var mediaPlayer; // To hold an instance of the media player
    var isMediaPlaying = false;
    var mediaDuration = 0;
    var progressBar;
    // In a real world app, you declare the media location variable with an empty string
    // and update it when a user chooses a media file from a local or remote source.
    var mediaLocation =
    "https://webdemo.agora.io/agora-web-showcase/examples/Agora-Custom-VideoSource-Web/assets/sample.mp4";

    var mediaButton;
    Copy

Implement media player functions

To implement playing and publishing media files in your app, take the following steps:

  1. Open, play and pause media files

    When a user presses the button for the first time, you create an instance of the media player, set its mediaPlayerObserver to receive the callbacks, and open the media file. When the user presses the button again, you play the media file. On subsequent button presses, you pause or resume playing the media file alternately. To do this, add the following method to preload.js before document.getElementById("leave").onclick = async function ():

    document.getElementById("mediaPlayer").onclick = async function ()
    {
    mediaButton = document.getElementById("mediaPlayer");
    // Initialize the mediaPlayer and open a media file
    if (mediaPlayer == null) {
    // Create an instance of the media player.
    mediaPlayer = agoraEngine.createMediaPlayer();
    // Set the mediaPlayerObserver to receive callbacks.
    mediaPlayer.registerPlayerSourceObserver(mediaPlayerObserver);
    // Open the media file
    mediaPlayer.open(mediaLocation, 0);
    // Update the mediaPlayer button text.
    mediaButton.innerHTML = 'Opening Media File...';
    return;
    }

    // Set up the local video container to handle the media player output
    // or the camera stream, alternately.
    isMediaPlaying = !isMediaPlaying;
    // Set the stream publishing options
    updateChannelPublishOptions(isMediaPlaying);
    // Display the stream locally
    setupLocalVideo(isMediaPlaying);

    let state = mediaPlayer.getState();
    if (isMediaPlaying)
    {
    // Start or resume playing media
    if (state == MediaPlayerState.PlayerStateOpenCompleted)
    {
    mediaPlayer.play();
    }
    else if (state == MediaPlayerState.PlayerStatePaused)
    {
    mediaPlayer.resume();
    }
    mediaButton.innerHTML = 'Pause Playing Media';
    }
    else
    {
    if (state == MediaPlayerState.PlayerStatePlaying)
    {
    // Pause media file
    mediaPlayer.pause();
    mediaButton.innerHTML = "Resume Playing Media";
    setupLocalVideo(false);
    updateChannelPublishOptions(false);
    }
    }
    }
    Copy
  2. Manage media player callbacks

    The IMediaPlayerSourceObserver implements media player callbacks. You create an instance of onPlayerSourceStateChanged and register it with the media player instance. When the player state changes, you take appropriate actions to update the UI in onPlayerStateChanged. You use the onPositionChanged callback to update the progress bar. To implement these callbacks, add the following code before const EventHandles = :

    const mediaPlayerObserver =
    {
    onPlayerSourceStateChanged: (state,error) =>
    {
    if (state == MediaPlayerState.PlayerStateOpenCompleted)
    {
    mediaDuration = mediaPlayer.getDuration();
    mediaButton.innerHTML = "Play Media File";
    }
    else if (state == MediaPlayerState.PlayerStatePlaybackAllLoopsCompleted)
    {
    isMediaPlaying = false;
    mediaButton.innerHTML = "Load Media File";
    // Clean up
    agoraEngine.destroyMediaPlayer(mediaPlayer);
    agoraEngine.destroyRendererByView(localVideoContainer);
    mediaPlayer = null;
    // Restore camera and microphone streams
    setupLocalVideo(false);
    updateChannelPublishOptions(false);
    // Refresh progress bar.
    progressBar.style.width = "0";
    }
    },
    onPositionChanged: (position) =>
    {
    if (mediaDuration > 0)
    {
    var result = parseInt( parseFloat(position) / parseFloat(mediaDuration) * 100);
    // Update ProgressBar as video forwards.
    progressBar = document.getElementById('bar');
    progressBar.style.width = result + "%";
    }
    }
    }
    Copy
  3. Configure Agora Engine to publish the media player stream

    You use ChannelMediaOptions and the updateChannelMediaOptions method to specify the type of stream to publish. To switch between publishing media player and camera and microphone streams, in preload.js, add the following method before window.onload = () => :

    function updateChannelPublishOptions(publishMediaPlayer)
    {
    let channelOptions = new ChannelMediaOptions();
    channelOptions.publishMediaPlayerAudioTrack = publishMediaPlayer;
    channelOptions.publishMediaPlayerVideoTrack = publishMediaPlayer;
    channelOptions.publishMicrophoneTrack = !publishMediaPlayer;
    channelOptions.publishCameraTrack = !publishMediaPlayer;
    if (publishMediaPlayer) channelOptions.publishMediaPlayerId = mediaPlayer.getMediaPlayerId();
    agoraEngine.updateChannelMediaOptions(channelOptions);
    }
    Copy
  4. Display media player output locally

    Setup a VideoCanvas and use it in the setupLocalVideo method of the Agora Engine to show the media player output locally. To switch between displaying media player output and the camera stream, in preload.js, add the following function before window.onload = () => :

    function setupLocalVideo(forMediaPlayer)
    {
    if (forMediaPlayer)
    {
    agoraEngine.destroyRendererByView(localVideoContainer);
    agoraEngine.setupLocalVideo(
    {
    sourceType: VideoSourceType.VideoSourceMediaPlayer,
    view: localVideoContainer,
    renderMode: RenderModeType.RenderModeFit,
    uid: mediaPlayer.getMediaPlayerId()
    });
    }
    else
    {
    agoraEngine.destroyRendererByView(localVideoContainer);
    agoraEngine.setupLocalVideo(
    {
    sourceType: VideoSourceType.VideoSourceCameraPrimary,
    view: localVideoContainer,
    renderMode: RenderModeType.RenderModeFit,
    });
    }
    }
    Copy
  5. Clean up when you close the app

    To free up resources when you exit the app, add the following lines to the document.getElementById("leave").onclick method before window.location.reload();:

    // Destroy the media player
    mediaPlayer.stop();
    mediaPlayer.unregisterPlayerSourceObserver(mediaPlayerObserver);
    agoraEngine.destroyMediaPlayer(mediaPlayer);
    Copy

Test your implementation

To ensure that you have implemented media player features into your app:

  1. Generate a temporary token in Agora Console .

  2. In your browser, navigate to the Agora web demo and update App ID, Channel, and Token with the values for your temporary token, then click Join.

  1. In preload.js, update appID, channel and token with your values.

  2. Run the app

    Execute the following command in the terminal:

    npm start
    Copy

    You see your app opens a window named Get started with Interactive Live Streaming.

  1. Select Host and press Join.
  1. Press Open Media File.

    Your app starts loading the media file into media player. When the loading finishes, the button text changes to Play Media File.

  2. Press Play Media File

    You see the media file played both locally and in the web demo app. The progress bar indicates the play progress.

  3. Press Pause Playing Media

    Media publishing is paused and the camera and microphone publishing is resumed.

  4. Press Resume Playing Media

    You see that the media file resumes playing.

  5. Wait for the media file to finish playing. When the progress bar reaches the end, the media player publishing is stopped and camera and microphone publishing is resumed.

Reference

This section contains information that completes the information in this page, or points you to documentation that explains other aspects to this product.

Interactive Live Streaming