Web Player

Last update:2025-06-24 14:24:29

This guide provides a comprehensive walkthrough for integrating our low-latency WebRTC player into your web application.

We will use the provided demo package as a starting point, breaking down how the demo.html file works so you can confidently adapt it for your own project.

Getting Started: Download the Demo Package

The demo package contains a complete, working example and all the necessary files to get started immediately.

The downloaded package includes:

  • demo.html: A functional example page with all HTML and JavaScript in one file.
  • wsrtcplayer.min.js: The core Software Development Kit (SDK).
  • css/ folder: Contains main.css and rtc_main.css for styling the demo page.

Understanding the Provided Demo

Let’s break down the demo.html file to understand how it uses the SDK to play a video stream.

Step 1: The HTML Structure

The demo.html file lays out the page’s visual elements. The most important parts are:

  • A <video> Element: This is where the video is displayed. It has a unique id so the JavaScript can target it.
  • Control Buttons: These buttons are used to start and stop the player.
  • The SDK Script Tag: This line loads the player library, making it available to the page. It must be included for the player to work.
  • The Inline Script Block: At the bottom of the file, a <script> block contains all the JavaScript logic to control the player.

Step 2: The JavaScript Logic (Inside demo.html)

Inside the <script> tag at the bottom of demo.html, you will find the code that controls the player. Let’s analyze its key parts.

a. The onEvent Callback

First, a function named onEvent is defined. Its purpose is to receive status updates from the player, such as when playback starts or when buffering occurs.

// This function handles all events dispatched from the player.
function onEvent(type, data) {
  switch (type) {
    case 3: // A custom event from the player
      console.log("Customer Event: " + data);
      break;
    case 2: // The server's SDP answer has been received
      console.log("SDP Answer Received.");
      break;
    case 1: // Buffering or stalling has occurred
      console.log("Buffering occurred.");
      break;
    case 0: // Playback has resumed after buffering
      console.log("Playback resumed.");
      break;
  }
}

b. Player Initialization and Control

Next, the code sets up the “Play” button. When playButton is clicked, the following sequence happens:

  1. Cleanup Old Player: The code checks if a player object already exists and calls player.destroy() to clean up all resources. This is a crucial step to prevent errors if the user clicks “Play” multiple times.
  2. Define Player Options: A new option object is created to configure the player.
  3. Create Player Instance: window.wsrtcplayer.createWSRTCPlayer(option) is called. This uses the SDK to create a new player instance.
  4. Start Playback: player.open(signal_url) is called to connect to the stream and begin playing.

Customizing the Demo

The provided demo.html file is a complete and functional starting point. Here are a few common ways you can customize it for your needs.

1. Using Your Customer ID (Required for Production)

The demo uses a placeholder customerID. For your production application, you must replace this with the unique Account Name provided to you by CDNetworks. This is essential for applying any custom server-side configurations to your service.

const playerOptions = {
    element: videoElement,
    customerID: "YOUR_UNIQUE_ACCOUNT_NAME", // Change this value
    listener: onEvent
};

2. Enabling Auto-Play on Page Load

By default, the demo waits for a user to click the “Play” button. To make the video play automatically as soon as the page loads, the script needs to be modified. Replace the entire <script> block at the bottom of demo.html with the following code:

<script>
    document.addEventListener('DOMContentLoaded', function () {
        
        // This function handles status updates from the player.
        function onEvent(type, data) {
            const timestamp = (window.performance.now() / 1000).toFixed(3);
            console.log(timestamp + ": Event received - Type: " + type);
        }

        const videoElement = document.getElementById('video-player');
        const signalUrl = 'http://webrtc-pull.test.cdnetworks.com/live/stream1.sdp';

        // Define the options for the player
        const playerOptions = {
            element: videoElement,
            customerID: "YOUR_UNIQUE_ACCOUNT_NAME", // Use your real Account Name
            listener: onEvent
        };

        // Create the player instance
        const player = window.wsrtcplayer.createWSRTCPlayer(playerOptions);

        // Start playback immediately
        if (player) {
            player.open(signalUrl);
        }
    });
</script>

Remember to replace the const signalUrl in the code with your own URL by which you wish to start the playback immediately.

<const signalUrl = 'http://webrtc-pull.test.cdnetworks.com/live/stream1.sdp';>

3. Displaying Player Status

You can use the onEvent listener to provide real-time feedback to your users. First, add a <div> to your HTML to hold the status messages:

<div id="status-display" style="padding: 10px; font-weight: bold;">Connecting...</div>

Next, modify your onEvent function to update this element’s text based on the player’s state:

const statusDisplay = document.getElementById('status-display');

function onEvent(type, data) {
  switch (type) {
    case 0:
      statusDisplay.innerText = 'Status: Playing';
      statusDisplay.style.color = 'green';
      break;
    case 1:
      statusDisplay.innerText = 'Status: Buffering...';
      statusDisplay.style.color = 'orange';
      break;
    case 2:
      statusDisplay.innerText = 'Status: Connected';
      break;
  }
}

4. Customizing the Player’s Appearance (CSS)

The demo uses two CSS files to give the page its simple, functional appearance: rtc_main.css (a generic base style) and main.css (demo-specific styles). You have complete freedom to change these styles or, for best results, override them with your own stylesheet to match your application’s branding.

Recommended Method: Create Your Own Stylesheet

  1. Create a new file named my-styles.css in your css folder.
  2. Add your custom CSS rules to this new file. For example:
    /* Inside /css/my-styles.css */
    #video-player {
      border: 3px solid #007bff;
      border-radius: 5px;
      box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    }
    
  3. Link your new stylesheet in demo.html after the other two CSS files. Placing it last ensures your styles will override the defaults.
    <link rel="stylesheet" href="css/rtc_main.css" />
    <link rel="stylesheet" href="css/main.css" />
    <link rel="stylesheet" href="css/my-styles.css" />
    

Quick Modification (for Testing)

If you simply want to test a style quickly, you can add the CSS rule to the end of the main.css file.

API Reference

createWSRTCPlayer(options)

Creates a player instance.

  • options (Object): A configuration object.
    • element (HTMLVideoElement) [Required]: The <video> element to use for playback.
    • customerID (String) [Optional]: Your unique Account Name, provided by CDNetworks. This links the player to your account for any custom server-side configurations.
    • listener (Function) [Optional]: A callback function to receive player events.

player.open(signal_url)

Starts loading and playing the video stream.

player.close()

Stops video playback and disconnects the stream.

player.destroy()

Stops playback, disconnects, and cleans up all internal resources used by the player instance. Call this when you are finished with a player instance to prevent memory leaks.

Event Callback (listener)

The callback function receives two parameters: function(type, data).

Parameter Type Description
type Number A code representing the event type. See the list below for details.
data String Event-specific data. This parameter is only populated for certain event types.

Event type Codes:

  • 0: Playback has resumed after buffering.
  • 1: Buffering or stalling has occurred.
  • 2: The SDP answer from the server has been received. The data parameter will contain the SDP information string.
  • 3: A custom event from the player. The data parameter will contain the custom event string.

Signaling URL Format

The signaling URL has the following structure: http(s)://domain/appName/streamName.sdp

  • domain: Your domain name added on Low Latency Streaming.
  • appName: The application name or publish point, which is the smallest unit for configurations like transcoding and recording, used for configuration isolation. It can be also used to seperate different live channel types.
  • streamName: The name of the live stream, used to differentiate one broadcast from another.

Browser Compatibility

Operating System Browser Type Minimum Version
Mac OS Desktop Safari 11+
Mac OS Desktop Chrome 47+
Windows Desktop Chrome 56+
Android Mobile Chrome 88+
iOS Mobile Safari 11+
iOS WeChat In-App Browser 12+

Note: Browsers based on the Chromium engine should follow the corresponding Chrome version requirements. Support on Android browsers may vary, and some devices may lack hardware decoding support for H.264.

Is the content of this document helpful to you?
Yes
I have suggestion
Submitted successfully! Thank you very much for your feedback, we will continue to strive to do better!