Web Player

Last update:2025-09-15 15:48:49

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 reference to break down how the player works, enabling you to adapt it for your own projects with confidence.

Getting Started

Before you begin, please download the demo package. It contains all the necessary files to get started immediately.

The 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/: A folder containing stylesheets for the demo.

Core Implementation: Click-to-Play

This section explains how to implement a basic player that starts playback when a user clicks a “Play” button, based on the demo.html file.

Step 1: Set Up the HTML Structure

Your HTML file needs three key elements to function:

  1. A <video> Element: The container where the video stream will be displayed.
  2. Player Controls: An input field for the stream URL and buttons to start/stop playback.
  3. The SDK <script>: The tag that loads the player library into your page.

Here is a simplified HTML structure:

<!DOCTYPE html>
<html>
<head>
    <title>WebRTC Player</title>
    <link rel="stylesheet" href="css/main.css" />
</head>
<body>
    <!-- 1. The video element for playback -->
    <!-- We recommend `muted` and `playsinline` to enable autoplay on most mobile browsers. -->
    <!-- `controls` provides a fallback to native browser playback controls. -->
    <video id="video-player" controls muted playsinline></video>

    <!-- 2. Controls for the player -->
    <input id="stream-url" type="text" value="http://webrtc-pull.test.cdnetworks.com/live/stream1.sdp">
    <button id="play-button">Play</button>
    <button id="stop-button">Stop</button>

    <!-- 3. The core SDK -->
    <script src="wsrtcplayer.min.js"></script>

    <!-- 4. Your custom script to control the player -->
    <script>
        // JavaScript logic goes here
    </script>
</body>
</html>

Step 2: Implement Player Logic in JavaScript

Next, add the JavaScript logic inside the final <script> tag to control the player.

document.addEventListener('DOMContentLoaded', function () {
    // Get references to HTML elements
    const playBtn = document.getElementById('play-button');
    const stopBtn = document.getElementById('stop-button');
    const videoElement = document.getElementById('video-player');
    const streamUrlInput = document.getElementById('stream-url');

    let player = null; // This will hold the player instance

    // 1. Define an event listener to handle player status updates
    function onPlayerEvent(type, data) {
        const timestamp = (performance.now() / 1000).toFixed(3);
        console.log(`${timestamp}s: Event - Type: ${type}, Data: ${data || 'N/A'}`);
    }

    // 2. Configure the "Play" button
    playBtn.onclick = function() {
        // Best practice: Always destroy the previous player instance before creating a new one.
        if (player) {
            player.destroy();
        }

        // Define player options
        const playerOptions = {
            element: videoElement, // The <video> element
            customerID: "YOUR_ACCOUNT_NAME", // IMPORTANT: Replace with your actual Account Name
            listener: onPlayerEvent // The event callback function
        };

        // Create a new player instance
        player = window.wsrtcplayer.createWSRTCPlayer(playerOptions);

        // Get the stream URL from the input field and start playback
        const streamUrl = streamUrlInput.value;
        if (player && streamUrl) {
            player.open(streamUrl);
        }
    };

    // 3. Configure the "Stop" button
    stopBtn.onclick = function() {
        if (player) {
            player.close();
        }
    };
});

Advanced Customizations

With the core implementation complete, your player is now functional. This section covers advanced configurations you can use to customize its behavior, such as enabling auto-play, displaying real-time player status, and changing the player’s appearance.

Auto-Play on Page Load

To make the video play automatically, you can initialize and open the player directly inside the DOMContentLoaded event listener. This approach removes the need for user interaction to start the stream.

document.addEventListener('DOMContentLoaded', function () {
    const videoElement = document.getElementById('video-player');
    const streamUrl = 'http://webrtc-pull.test.cdnetworks.com/live/stream1.sdp'; // Replace with your stream URL

    function onPlayerEvent(type, data) {
        const timestamp = (performance.now() / 1000).toFixed(3);
        console.log(`${timestamp}s: Event - Type: ${type}, Data: ${data || 'N/A'}`);
    }

    const playerOptions = {
        element: videoElement,
        customerID: "YOUR_ACCOUNT_NAME", // Replace with your Account Name
        listener: onPlayerEvent
    };

    // Create and start the player immediately
    const player = window.wsrtcplayer.createWSRTCPlayer(playerOptions);
    if (player) {
        player.open(streamUrl);
    }

    // Optional: Clean up resources when the user navigates away
    window.addEventListener('beforeunload', () => {
        if (player) {
            player.destroy();
        }
    });
});

Displaying Player Status

You can provide real-time feedback to users by updating the UI based on player events.

First, add a <div> to your HTML to display status messages:

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

Next, modify your onPlayerEvent function to update this element based on the event type.

function onPlayerEvent(type, data) {
    const statusDisplay = document.getElementById('status-display');

    switch (type) {
        case 0: // Playing
            statusDisplay.innerText = 'Status: Playing';
            statusDisplay.style.color = 'green';
            break;
        case 1: // Buffering
            statusDisplay.innerText = 'Status: Buffering...';
            statusDisplay.style.color = 'orange';
            break;
        case 2: // Connected
            statusDisplay.innerText = 'Status: Connected';
            statusDisplay.style.color = 'blue';
            break;
        default:
            console.log(`Event: ${type}`);
            break;
    }
}

Customizing Player Appearance with CSS

The demo uses rtc_main.css and main.css. To customize the player’s appearance, create your own stylesheet (e.g., my-styles.css) and link it in your HTML after the default stylesheets. This ensures your styles take precedence.

  1. Create css/my-styles.css and add your custom rules:

    /* /css/my-styles.css */
    #video-player {
      border: 3px solid #007bff;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    }
    
    
  2. Link it in your HTML:

    <link rel="stylesheet" href="css/rtc_main.css" />
    <link rel="stylesheet" href="css/main.css" />
    <link rel="stylesheet" href="css/my-styles.css" />
    
    

API Reference

Method Parameters Description
createWSRTCPlayer(options) options (Object):
element (HTMLVideoElement): The <video> element for playback. (Required)
customerID (String): Your unique Account Name. (Optional)
listener (Function) : A callback function to receive player events. (Optional)
Creates a player instance.
player.open(signal_url) signal_url (String): The URL for the streaming signal. Connects to the signaling server, establishes the WebRTC peer connection, and begins playing the video stream.
player.close() (none) Stops video playback and disconnects the stream.
player.destroy() (none) Stops playback, disconnects, and cleans up all internal resources. Call this when finished with a player to prevent memory leaks.

Event Listener

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

Argument Type Description
type Number A code representing the event type (see list below).
data String Additional data associated with the event.

Event type Codes:

  • 0: Playback started or resumed after buffering.
  • 1: Buffering has occurred.
  • 2: SDP answer received from the server. data contains the SDP string.
  • 3: A custom event from the player. data contains the event string.

Signaling URL Format

The signaling URL follows this structure: http(s)://<domain>/<appName>/<streamName>.sdp

  • domain: Your domain configured for Low Latency Streaming.
  • appName: The application name used for configuration (e.g., live).
  • streamName: The unique name of the live stream.

Browser Compatibility

OS Browser Minimum Version
macOS Safari (Desktop) 11+
macOS Chrome (Desktop) 47+
Windows Chrome (Desktop) 56+
Android Chrome (Mobile) 88+
iOS Safari (Mobile) 11+
iOS WeChat (In-App) 12+

Note: Browsers based on the Chromium engine generally follow Chrome’s version requirements. Support on Android may vary, as some devices lack hardware decoding 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!