HLS.js - JavaScript HLS Client

1.6.16 · active · verified Sun Apr 19

HLS.js is a robust, open-source JavaScript library that implements an HLS (HTTP Live Streaming) client. It enables the playback of HLS streams directly in modern web browsers by leveraging the Media Source Extensions (MSE) API, eliminating the need for native browser HLS support. The current stable version is 1.6.16, with frequent patch releases addressing bug fixes and performance improvements. An active pre-release series, such as 1.7.0-alpha.1, indicates continuous development and upcoming significant changes. HLS.js differentiates itself through its extensive feature set, including adaptive bitrate streaming, DVR support, low-latency HLS (LL-HLS), DRM (via EME), CEA-608/708 captions, WebVTT subtitles, and advertising insertion, making it a comprehensive solution for HLS playback in web applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize HLS.js, attach it to an HTML5 video element, load an HLS manifest, and handle common fatal errors for recovery. It includes a check for browser compatibility and a fallback for native HLS playback.

import Hls from 'hls.js';

const video = document.getElementById('video') as HTMLVideoElement;
const manifestUrl = 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8';

if (Hls.isSupported()) {
  const hls = new Hls({
    // Example configuration for a live stream with limited back buffer
    liveSyncDurationCount: 3,
    liveMaxLatencyDuration: 10,
    // workerPath: '/path/to/hls.worker.js' // Required if using ESM build with workers
  });

  hls.on(Hls.Events.MEDIA_ATTACHED, () => {
    console.log('Media attached to video element.');
    hls.loadSource(manifestUrl);
  });

  hls.on(Hls.Events.MANIFEST_PARSED, (event, data) => {
    console.log(`Manifest loaded, found ${data.levels.length} quality level(s).`);
    // Optionally set quality level, e.g., to the highest available
    // hls.currentLevel = data.levels.length - 1;
    video.play();
  });

  hls.on(Hls.Events.ERROR, (event, data) => {
    if (data.fatal) {
      console.error(`Hls.js fatal error: ${data.type} - ${data.details}`, data);
      switch (data.type) {
        case Hls.ErrorTypes.NETWORK_ERROR:
          console.error('Network error detected, trying to recover...');
          hls.startLoad();
          break;
        case Hls.ErrorTypes.MEDIA_ERROR:
          console.error('Media error detected, trying to recover...');
          hls.recoverMediaError();
          break;
        default:
          // Cannot recover
          hls.destroy();
          break;
      }
    }
  });

  hls.attachMedia(video);
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
  // Native HLS support for Safari, etc.
  video.src = manifestUrl;
  video.addEventListener('loadedmetadata', () => {
    video.play();
  });
} else {
  console.error('This browser does not support HLS playback.');
}

view raw JSON →