hls.js、plyr、plyr-react、react-player、video.js 和 videojs-record 都是用于在 Web 应用中处理视频播放和录制的 JavaScript 库,但它们的设计目标和适用场景各不相同。
hls.js 专注于 HLS 流媒体协议支持,让不支持 HLS 的浏览器也能播放 HLS 流。
plyr 提供统一的视频播放器 UI 界面,支持 HTML5、YouTube、Vimeo 等多种来源。
plyr-react 是 plyr 的 React 封装版本,但需要注意其维护状态。
react-player 是 React 组件,支持多种视频平台(YouTube、Vimeo、本地文件等),强调易用性。
video.js 是功能最完整的专业视频播放器框架,支持丰富的插件生态。
videojs-record 是 video.js 的录制插件,用于实现视频录制功能。
在 Web 应用中处理视频播放和录制时,开发者面临多个技术选择。hls.js、plyr、plyr-react、react-player、video.js 和 videojs-record 各自解决不同的问题。本文将从核心技术架构、API 设计、React 集成、功能扩展等维度进行深度对比。
hls.js 是 HLS 流媒体协议播放器,专注于让不支持 HLS 的浏览器能够播放 HLS 流。
// hls.js: 直接绑定到 video 元素
import Hls from 'hls.js';
const video = document.getElementById('video');
const hls = new Hls();
hls.loadSource('https://example.com/stream.m3u8');
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, () => video.play());
plyr 是 UI 统一的视频播放器包装器,支持多种视频来源。
// plyr: 初始化播放器
import Plyr from 'plyr';
const player = new Plyr('#player', {
controls: ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', 'fullscreen'],
captions: { active: true }
});
plyr-react 是 plyr 的 React 封装版本。
// plyr-react: React 组件用法
import Plyr from 'plyr-react';
import 'plyr-react/plyr.css';
function VideoPlayer() {
return (
<Plyr
source={{
type: 'video',
sources: [{ src: 'https://example.com/video.mp4', type: 'video/mp4' }]
}}
/>
);
}
react-player 是 React 组件,支持多种视频平台。
// react-player: 多平台支持
import ReactPlayer from 'react-player';
function VideoPlayer() {
return (
<ReactPlayer
url='https://www.youtube.com/watch?v=xyz'
width='100%'
height='100%'
controls={true}
/>
);
}
video.js 是专业级视频播放器框架。
// video.js: 完整播放器初始化
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
const player = videojs('my-video', {
autoplay: true,
controls: true,
sources: [{
src: 'https://example.com/video.mp4',
type: 'video/mp4'
}]
});
videojs-record 是 video.js 的录制插件。
// videojs-record: 启用录制功能
import videojs from 'video.js';
import 'videojs-record/dist/css/videojs.record.css';
import 'videojs-record/dist/videojs.record.js';
const player = videojs('my-video', {
controls: true,
plugins: {
record: {
audio: true,
video: true,
maxLength: 10,
debug: true
}
}
});
player.on('finishRecord', () => {
const recordedBlob = player.recordedData;
// 处理录制的视频数据
});
HLS(HTTP Live Streaming)是现代视频流媒体的重要协议,各包支持程度不同。
hls.js 原生支持 HLS,这是它的核心功能。
// hls.js: HLS 播放
import Hls from 'hls.js';
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource('https://example.com/stream.m3u8');
hls.attachMedia(videoElement);
} else if (videoElement.canPlayType('application/vnd.apple.mpegurl')) {
// Safari 原生支持
videoElement.src = 'https://example.com/stream.m3u8';
}
plyr 需要配合 hls.js 使用才能播放 HLS。
// plyr + hls.js: 组合使用
import Hls from 'hls.js';
import Plyr from 'plyr';
const video = document.getElementById('player');
const hls = new Hls();
hls.loadSource('https://example.com/stream.m3u8');
hls.attachMedia(video);
const player = new Plyr(video);
plyr-react 同样需要配合 hls.js。
// plyr-react + hls.js
import Plyr from 'plyr-react';
import Hls from 'hls.js';
import { useEffect, useRef } from 'react';
function HlsPlayer({ source }) {
const videoRef = useRef(null);
useEffect(() => {
if (Hls.isSupported() && videoRef.current) {
const hls = new Hls();
hls.loadSource(source);
hls.attachMedia(videoRef.current);
}
}, [source]);
return <Plyr ref={videoRef} />;
}
react-player 内置 HLS 支持(通过 hls.js)。
// react-player: 内置 HLS
import ReactPlayer from 'react-player';
function HlsVideo() {
return (
<ReactPlayer
url='https://example.com/stream.m3u8'
config={{
file: {
forceHLS: true
}
}}
/>
);
}
video.js 需要额外插件支持 HLS(videojs-http-streaming 已内置在 v7+)。
// video.js: HLS 支持(v7+ 内置)
import videojs from 'video.js';
const player = videojs('my-video', {
sources: [{
src: 'https://example.com/stream.m3u8',
type: 'application/x-mpegURL'
}]
});
videojs-record 继承 video.js 的 HLS 能力。
// videojs-record: 录制 + HLS 播放
const player = videojs('my-video', {
sources: [{
src: 'https://example.com/stream.m3u8',
type: 'application/x-mpegURL'
}],
plugins: {
record: {
audio: false, // 直播流通常不录制
video: false
}
}
});
在 React 项目中使用这些库的体验差异明显。
hls.js 需要手动管理生命周期。
// hls.js + React
import { useEffect, useRef } from 'react';
import Hls from 'hls.js';
function HlsVideo({ src }) {
const videoRef = useRef(null);
useEffect(() => {
const hls = new Hls();
hls.loadSource(src);
hls.attachMedia(videoRef.current);
return () => {
hls.destroy();
};
}, [src]);
return <video ref={videoRef} controls />;
}
plyr 同样需要手动初始化。
// plyr + React
import { useEffect, useRef } from 'react';
import Plyr from 'plyr';
import 'plyr/dist/plyr.css';
function PlyrVideo({ source }) {
const videoRef = useRef(null);
useEffect(() => {
const player = new Plyr(videoRef.current);
return () => player.destroy();
}, []);
return (
<video ref={videoRef}>
<source src={source} type="video/mp4" />
</video>
);
}
plyr-react 提供现成的 React 组件。
// plyr-react: 开箱即用
import Plyr from 'plyr-react';
import 'plyr-react/plyr.css';
function VideoPlayer({ source }) {
return (
<Plyr
source={{
type: 'video',
sources: [{ src: source, type: 'video/mp4' }]
}}
options={{ controls: ['play', 'progress', 'volume'] }}
/>
);
}
react-player 是最简单的 React 集成方案。
// react-player: 最简用法
import ReactPlayer from 'react-player';
function VideoPlayer({ url }) {
return <ReactPlayer url={url} controls width='100%' />;
}
video.js 需要配合 React 封装。
// video.js + React
import { useEffect, useRef } from 'react';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
function VideoJSPlayer({ options }) {
const videoRef = useRef(null);
const playerRef = useRef(null);
useEffect(() => {
playerRef.current = videojs(videoRef.current, options);
return () => {
if (playerRef.current) {
playerRef.current.dispose();
}
};
}, [options]);
return (
<div>
<video ref={videoRef} className="video-js" />
</div>
);
}
videojs-record 继承 video.js 的 React 集成方式。
// videojs-record + React
import { useEffect, useRef } from 'react';
import videojs from 'video.js';
function RecordPlayer() {
const videoRef = useRef(null);
useEffect(() => {
const player = videojs(videoRef.current, {
controls: true,
plugins: {
record: {
audio: true,
video: true,
maxLength: 10
}
}
});
return () => player.dispose();
}, []);
return <video ref={videoRef} className="video-js" />;
}
播放器的 UI 定制程度影响品牌一致性和用户体验。
hls.js 不提供 UI,完全自定义。
// hls.js: 完全自定义 UI
const video = document.getElementById('video');
const hls = new Hls();
hls.loadSource('stream.m3u8');
hls.attachMedia(video);
// 自定义控制按钮
document.getElementById('play-btn').onclick = () => video.play();
document.getElementById('pause-btn').onclick = () => video.pause();
plyr 提供预设 UI,支持 CSS 定制。
// plyr: CSS 定制
const player = new Plyr('#player', {
controls: ['play', 'progress', 'volume'],
tooltips: { controls: true }
});
/* CSS 定制 */
.plyr--video {
--plyr-color-main: #007bff;
}
plyr-react 继承 plyr 的 UI 定制能力。
// plyr-react: 通过 options 定制
<Plyr
source={{ type: 'video', sources: [{ src: 'video.mp4' }] }}
options={{
controls: ['play-large', 'play', 'progress'],
settings: ['quality', 'speed']
}}
/>
react-player UI 定制有限,依赖各平台原生控件。
// react-player: 有限定制
<ReactPlayer
url='https://youtube.com/watch?v=xyz'
controls={true}
width='800px'
height='450px'
config={{
youtube: {
playerVars: { showinfo: 0 }
}
}}
/>
video.js 提供丰富的主题和插件系统。
// video.js: 主题定制
import videojs from 'video.js';
import 'video.js/dist/themes/sea.css';
const player = videojs('my-video', {
theme: 'sea'
});
// 自定义控件
player.controlBar.addChild('MyCustomButton');
videojs-record 继承 video.js 的 UI 系统。
// videojs-record: 录制 UI
const player = videojs('my-video', {
plugins: {
record: {
audio: true,
video: true,
displayMilliseconds: true
}
}
});
// 录制按钮自动添加到控制栏
hls.js 插件生态较小,主要通过 API 扩展。
// hls.js: 事件监听扩展
hls.on(Hls.Events.FRAG_LOADED, (event, data) => {
console.log('Fragment loaded:', data.frag);
});
hls.on(Hls.Events.ERROR, (event, data) => {
if (data.fatal) {
hls.startLoad();
}
});
plyr 插件较少,主要通过配置扩展。
// plyr: 事件监听
player.on('play', () => {
console.log('Video started playing');
});
player.on('timeupdate', (event) => {
console.log('Current time:', player.currentTime);
});
plyr-react 继承 plyr 的事件系统。
// plyr-react: 事件处理
<Plyr
source={{ type: 'video', sources: [{ src: 'video.mp4' }] }}
onPlay={(player) => console.log('Playing')}
onPause={(player) => console.log('Paused')}
/>
react-player 提供统一的事件接口。
// react-player: 统一事件
<ReactPlayer
url='https://example.com/video.mp4'
onPlay={() => console.log('Playing')}
onPause={() => console.log('Paused')}
onProgress={({ played, loaded }) => console.log(played)}
onEnded={() => console.log('Video ended')}
/>
video.js 拥有最丰富的插件生态。
// video.js: 插件使用
import videojs from 'video.js';
import 'videojs-contrib-ads';
import 'videojs-ima';
const player = videojs('my-video');
player.ima(); // Google IMA 广告插件
videojs-record 本身就是 video.js 的插件。
// videojs-record: 录制事件
player.on('startRecord', () => {
console.log('Recording started');
});
player.on('finishRecord', () => {
const blob = player.recordedData;
console.log('Recording finished:', blob);
});
plyr-react 需要特别注意:该包的社区维护活跃度相对较低。在正式项目中使用时,建议:
// 备选方案:直接使用 plyr
import { useEffect, useRef } from 'react';
import Plyr from 'plyr';
function SafeVideoPlayer({ source }) {
const videoRef = useRef(null);
useEffect(() => {
const player = new Plyr(videoRef.current);
return () => player.destroy();
}, []);
return (
<video ref={videoRef}>
<source src={source} type="video/mp4" />
</video>
);
}
其他包(hls.js、plyr、react-player、video.js、videojs-record)目前维护状态良好,可放心用于生产环境。
| 功能特性 | hls.js | plyr | plyr-react | react-player | video.js | videojs-record |
|---|---|---|---|---|---|---|
| HLS 支持 | ✅ 原生 | ⚠️ 需配合 | ⚠️ 需配合 | ✅ 内置 | ✅ v7+ 内置 | ✅ 继承 |
| React 支持 | ⚠️ 手动 | ⚠️ 手动 | ✅ 组件 | ✅ 组件 | ⚠️ 手动 | ⚠️ 手动 |
| 多平台支持 | ❌ | ✅ | ✅ | ✅ | ⚠️ 需插件 | ⚠️ 需插件 |
| UI 定制 | ✅ 完全 | ✅ CSS | ✅ CSS | ⚠️ 有限 | ✅ 主题 | ✅ 主题 |
| 录制功能 | ❌ | ❌ | ❌ | ❌ | ⚠️ 需插件 | ✅ 内置 |
| 插件生态 | ⚠️ 小 | ⚠️ 小 | ⚠️ 小 | ⚠️ 小 | ✅ 丰富 | ✅ 继承 |
| 维护状态 | ✅ 活跃 | ✅ 活跃 | ⚠️ 一般 | ✅ 活跃 | ✅ 活跃 | ✅ 活跃 |
选择 hls.js 如果:
选择 plyr 如果:
选择 plyr-react 如果:
plyr + React refs选择 react-player 如果:
选择 video.js 如果:
选择 videojs-record 如果:
没有"最好"的播放器,只有最适合场景的选择:
react-player 或 plyrhls.js 或 video.jsvideo.js + 插件生态videojs-recordreact-player记住:在正式项目中,务必验证所选包的维护状态和长期支持计划。
选择 hls.js 当你需要播放 HLS 流媒体内容,且目标浏览器不原生支持 HLS(如 Chrome、Firefox 桌面端)。适合直播、点播等需要自适应码率的场景。如果你的项目只需要 HLS 播放功能,不需要复杂 UI 定制,这是最轻量的选择。
选择 plyr 当你需要统一的播放器 UI 界面,支持多种视频来源(HTML5、YouTube、Vimeo),且项目不使用 React 或需要原生 JavaScript 实现。适合需要快速部署、UI 美观的营销网站或内容平台。
选择 plyr-react 需谨慎,该包社区维护活跃度较低。如果项目已使用 plyr 且需要 React 集成,可考虑使用,但建议评估直接使用 plyr + React refs 或选择 react-player 作为替代方案。
选择 react-player 当你的项目基于 React,需要快速集成多种视频平台(YouTube、Vimeo、本地文件、HLS 等),且不需要深度定制播放器底层行为。适合内容聚合类应用、博客、教育平台等。
选择 video.js 当你需要专业级视频播放解决方案,支持丰富的插件生态、广告插入、DRM、多语言字幕等高级功能。适合视频平台、流媒体服务、企业级应用等需要高度定制的场景。
选择 videojs-record 当你的项目已使用 video.js,且需要添加视频录制功能(摄像头、屏幕录制)。这是 video.js 生态中成熟的录制插件,适合需要录制功能的视频应用。
HLS.js is a JavaScript library that implements an HTTP Live Streaming client. It relies on HTML5 video and MediaSource Extensions for playback, and on Managed Media Source where MSE is not available (Safari on iOS 17.1+).
It streams VOD, Live, and Low-Latency HLS assets made up of fragmented MP4 (fMP4), MPEG-2 Transport Stream, or Packed Audio segments. fMP4 segments (ISO BMFF, including CMAF) are passed through to MSE without remuxing, while MPEG-2 TS and Packed Audio (AAC, MP3, and AC-3) segments are transmuxed into fMP4. Transmuxing is performed asynchronously using a Web Worker when available in the browser.
HLS.js streams media into a standard HTML <video> element, which handles decoding, rendering, playback, and seeking.
Control playback through the HTMLMediaElement API, and use HLS.js to load assets, choose quality levels and tracks, and listen for streaming events.
For assets with Interstitials, use hls.interstitialsManager to seek and track position on the integrated timeline of primary content and interstitial breaks.
HLS.js is written in TypeScript and transpiled using Babel to ECMAScript 5 syntax for the UMD bundles, and to native ES module syntax for the ESM bundles.
The TypeScript compiler and API Extractor are used for type checking and to generate the hls.d.ts type declarations.
Rollup is used to build the distro bundles and, in watch mode, the local development environment. Each release includes:
full and light builds. The light build leaves out optional features such as alternate audio, subtitles, EME (DRM), CMCD, and Interstitials to reduce size (see Build tasks).hls.js, hls.light.js) for <script> tags and require. They target browsers as old as Chrome 47, Firefox 51, and Safari 10, and inline the transmuxer worker.hls.mjs, hls.light.mjs) for import and modern bundlers. They do not inline the worker; set workerPath to the published hls.worker.js to transmux off the main thread.See Compatibility for supported browsers and runtime requirements.
SUPPLEMENTAL-CODECS attribute for codec selectionenableEmsgKLVMetadata)mjpg) renditionsFor details on the HLS format and these tags' meanings, see https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis
#EXT-X-STREAM-INF:<attribute-list>
<URI>#EXT-X-I-FRAME-STREAM-INF I-frame Media Playlist files#EXT-X-MEDIA:<attribute-list>#EXT-X-SESSION-DATA:<attribute-list>#EXT-X-SESSION-KEY:<attribute-list> EME Key-System selection and preloading#EXT-X-START:TIME-OFFSET=<n>#EXT-X-CONTENT-STEERING:<attribute-list> Content Steering#EXT-X-DEFINE:<attribute-list> Variable Substitution (NAME,VALUE,QUERYPARAM attributes)#EXTM3U (required format identifier)#EXT-X-VERSION:<n> (value is ignored)#EXT-X-INDEPENDENT-SEGMENTS (ignored)#EXT-X-I-FRAMES-ONLY#EXTINF:<duration>,[<title>]#EXT-X-ENDLIST#EXT-X-PLAYLIST-TYPE:<type-enum> (see "Not Supported" below)#EXT-X-MEDIA-SEQUENCE:<n>#EXT-X-TARGETDURATION:<n>#EXT-X-DISCONTINUITY#EXT-X-DISCONTINUITY-SEQUENCE:<n>#EXT-X-BITRATE:<rate>#EXT-X-BYTERANGE:<n>[@<o>]#EXT-X-MAP:<attribute-list>#EXT-X-KEY:<attribute-list> (KEYFORMAT="identity",METHOD=SAMPLE-AES is only supported with MPEG-2 TS segments)#EXT-X-PROGRAM-DATE-TIME:<date-time-msec>#EXT-X-START:TIME-OFFSET=<n>#EXT-X-SERVER-CONTROL:<attribute-list>#EXT-X-PART-INF:PART-TARGET=<n>#EXT-X-PART:<attribute-list>#EXT-X-SKIP:<attribute-list> Delta Playlists#EXT-X-RENDITION-REPORT:<attribute-list>#EXT-X-DATERANGE:<attribute-list> Metadata
#EXT-X-DEFINE:<attribute-list> Variable Import and Substitution (NAME,VALUE,IMPORT,QUERYPARAM attributes)#EXT-X-GAP (Skips loading GAP segments and parts. Skips playback of unbuffered program containing only GAP content and no suitable alternates. See #2940)Parsed but missing feature support:
#EXT-X-PRELOAD-HINT:<attribute-list> (See #5074)For a complete list of issues, see "Top priorities" in the Release Planning and Backlog project tab. Codec support is dependent on the runtime environment (for example, not all browsers on the same OS support HEVC).
REQ-VIDEO-LAYOUT is not used in variant filtering or selectionSAMPLE-AES method keys with fmp4, aac, mp3, vtt... segments (MPEG-2 TS only)org.w3.clearkey) is incomplete: the key system is recognized, but there is no way to supply key ID/key value pairs to the EME controller, so no license or session path exists (See #2934)light build (see __USE_M2TS_ADVANCED_CODECS__)require from a Node.js runtimeYou can safely require this library in Node and absolutely nothing will happen. A dummy object is exported so that requiring the library does not throw an error. HLS.js is not instantiable in Node.js. See #1841 for more details.
First, checkout the repository and install the required dependencies
git clone https://github.com/video-dev/hls.js.git
cd hls.js
# After cloning or pulling from the repository, make sure all dependencies are up-to-date
npm install ci
# Run dev-server for demo page (recompiles on file-watch, but doesn't write to actual dist fs artifacts)
npm run dev
# After making changes run the sanity-check task to verify all checks before committing changes
npm run sanity-check
The dev server will host files on port 8000. Once started, the demo can be found running at http://localhost:8000/demo/.
Before submitting a PR, please see our contribution guidelines. Join the discussion on Slack via video-dev.org in #hlsjs for updates and questions about development.
Build all flavors (suitable for prod-mode/CI):
npm install ci
npm run build
Only debug-mode artifacts:
npm run build:debug
Build and watch (customized dev setups where you'll want to host through another server - for example in a sub-module/project)
npm run build:watch
Only specific flavors (known configs are: full, fullMin, fullEsm, fullEsmMin, light, lightMin, lightEsm, lightEsmMin, worker, demo):
npm run build -- --configType fullMin # repeat --configType to build more than one
Report the size of the built dist/ files, and check them against the budgets in
dist-size-budget.json (the same check CI runs):
npm run size
npm run size:check
NOTE: hls.light.*.js dist files do not include alternate-audio, subtitles, CMCD, EME (DRM), Variable Substitution, Interstitials, I-frame trick-play, Media Capabilities, or MPEG-2 TS advanced codec (HEVC and AC-3) support. Content Steering is included. In addition, the following types are not available in the light build:
AudioStreamControllerAudioTrackControllerCuesInterfaceEMEControllerSubtitleStreamControllerSubtitleTrackControllerTimelineControllerCMCDControllerInterstitialsControllerInterstitialsManagerIFrameControllerHlsIFramesOnlyHlsImageIFramesOnlyRun linter:
npm run lint
Run linter with auto-fix mode:
npm run lint:fix
Run linter with errors only (no warnings)
npm run lint:quiet
Run prettier to format code
npm run prettier
Run type-check to verify TypeScript types
npm run type-check
Run all tests at once:
npm test
Run unit tests:
npm run test:unit
Run unit tests in watch mode:
npm run test:unit:watch
Run functional (integration) tests:
npm run test:func
An overview of this project's design, it's modules, events, and error handling can be found here.
Note you can access the docs for a particular version using "https://github.com/video-dev/hls.js/tree/deployments"
https://hlsjs.video-dev.org/demo
https://hlsjs-dev.video-dev.org/demo
Find the commit on https://github.com/video-dev/hls.js/tree/deployments.
This project is tested with BrowserStack. This project is tested with SauceLabs.
HLS.js is only compatible with browsers supporting MediaSource extensions (MSE) API with 'video/MP4' mime-type inputs.
HLS.js is supported on:
These versions are the targets passed to @babel/preset-env when building the UMD bundles in dist/. They share an ES2016 runtime baseline: ES5-style syntax plus native ES2016 globals (Map, Set, Promise, Array.from, Uint8Array.from, Array.prototype.includes, etc.). To keep bundle size small, no core-js polyfills are bundled.
Optional features such as CMCD pull in ES2017 APIs (e.g. Object.entries), so the full UMD bundle effectively requires an ES2017-capable runtime. The light bundle excludes those features and stays at the ES2016 baseline.
The dist/ folder ships two distribution variants:
dist/hls.js, dist/hls.min.js, dist/hls.light.js, dist/hls.light.min.js) — embeddable directly via a <script> tag (exposes a global Hls) or resolved by require('hls.js') via package.json's main field. Targets the browser list above. The companion dist/hls.worker.js is the bundled transmuxer Web Worker.dist/hls.mjs, dist/hls.light.mjs, plus the minified dist/hls.min.mjs and dist/hls.light.min.mjs) — import 'hls.js' resolves to the unminified dist/hls.mjs via the module field, which is what you want when a bundler will minify it for you. The .min.mjs files exist for loading straight from a CDN with <script type="module">. Built with @babel/preset-env's esmodules: true target (≈ Chrome 61+, Firefox 60+, Safari 10.1+, Edge 16+) and intended to be consumed by a modern bundler. Uses ES2015+ syntax but stays below ES2019 (no Array.prototype.flatMap, Object.fromEntries, etc.).The ESM builds do not bundle the transmuxer Web Worker. The UMD builds inline it, but
dist/hls.mjsanddist/hls.min.mjsdo not, so transmuxing runs on the main thread unless you pointworkerPathat the separately published worker:const hls = new Hls({ workerPath: 'https://cdn.jsdelivr.net/npm/hls.js@1/dist/hls.worker.js', });
If you import from src/ directly or include any of our runtime dependencies untranspiled in your own build, you bypass this Babel pipeline and become responsible for transpilation; those source modules can reach for ES2019+ APIs that are tree-shaken out of the bundles we publish.
To run on browsers below this baseline, supply your own polyfills for any missing globals before HLS.js loads.
Please note:
Safari browsers (iOS, iPadOS, and macOS) have built-in HLS support through the plain video "tag" source URL. See the example below (Using HLS.js) to run appropriate feature detection and choose between using HLS.js or natively built-in HLS support.
When a platform has neither MediaSource nor native HLS support, the browser cannot play HLS.
Keep in mind that if the intention is to support HLS on multiple platforms, beyond those compatible with HLS.js, HLS assets need to strictly follow the specifications of RFC8216, especially if apps, smart TVs, and set-top boxes are to be supported.
Find a support matrix of the MediaSource API here: https://developer.mozilla.org/en-US/docs/Web/API/MediaSource
Prepackaged builds are included with each release. Or install the hls.js as a dependency of your project:
npm install --save hls.js
A canary channel is also available if you prefer to work off the development branch (master):
npm install hls.js@canary
Directly include dist/hls.js or dist/hls.min.js in a script tag on the page. This setup prioritizes streaming with HLS.js and MSE over native browser support for HLS playback in HTMLMediaElements:
<script src="https://cdn.jsdelivr.net/npm/hls.js@1"></script>
<!-- Or if you want the latest version from the main branch -->
<!-- <script src="https://cdn.jsdelivr.net/npm/hls.js@canary"></script> -->
<video id="video"></video>
<script>
var video = document.getElementById('video');
var videoSrc = 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8';
if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource(videoSrc);
hls.attachMedia(video);
}
// HLS.js is not supported on platforms that do not have Media Source
// Extensions (MSE) enabled.
//
// When the browser has built-in HLS support (check using `canPlayType`),
// we can provide an HLS manifest (i.e. .m3u8 URL) directly to the video
// element through the `src` property. This is using the built-in support
// of the plain video element, without using HLS.js.
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = videoSrc;
}
</script>
To check for native browser support first and then fallback to HLS.js, swap these conditionals.
Note:
video.canPlayType('application/vnd.apple.mpegurl')returns a non-empty string ("maybe") in Safari, Chrome, and potentially other browsers. However, not all browsers support HLS content equally — for example, Chrome 147 reports support but may fail to play certain assets natively. UsingHls.isSupported()first (the default setup above) is recommended unless you specifically need native playback.
<script src="https://cdn.jsdelivr.net/npm/hls.js@1"></script>
<!-- Or if you want the latest version from the main branch -->
<!-- <script src="https://cdn.jsdelivr.net/npm/hls.js@canary"></script> -->
<video id="video"></video>
<script>
var video = document.getElementById('video');
var videoSrc = 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8';
//
// Only use native HLS in browsers with ManagedMediaSource (e.g. modern Safari)
// where native playback is well-supported. Other browsers may report HLS support
// via canPlayType but fail to play certain assets reliably.
//
if (
video.canPlayType('application/vnd.apple.mpegurl') &&
'ManagedMediaSource' in window
) {
video.src = videoSrc;
//
// If not using native HLS, check if HLS.js is supported
//
} else if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource(videoSrc);
hls.attachMedia(video);
}
</script>
HLS transcoding of an original video file often pushes the time of the first frame a bit. If you depend on having an exact match of frame times between original video and HLS asset, you need to account for this:
let tOffset = 0;
const getAppendedOffset = (eventName, { frag }) => {
if (frag.type === 'main' && frag.sn !== 'initSegment' && frag.elementaryStreams.video) {
const { start, startDTS, startPTS, maxStartPTS, elementaryStreams } = frag;
tOffset = elementaryStreams.video.startPTS - start;
hls.off(Hls.Events.BUFFER_APPENDED, getAppendedOffset);
console.log('video timestamp offset:', tOffset, { start, startDTS, startPTS, maxStartPTS, elementaryStreams });
}
}
hls.on(Hls.Events.BUFFER_APPENDED, getAppendedOffset);
// and account for this offset, for example like this:
const video = document.querySelector('video');
video.addEventListener('timeupdate', () => setTime(Math.max(0, video.currentTime - tOffset))
const seek = (t) => video.currentTime = t + tOffset;
const getDuration = () => video.duration - tOffset;
For more embed and API examples see docs/API.md.
All HLS resources must be delivered with CORS headers permitting GET requests.
Video is controlled through HTML <video> element HTMLVideoElement methods, events and optional UI controls (<video controls>).
The following players integrate HLS.js for HLS playback:
![]() | |||
![]() | ![]() | ![]() | |
![]() | ![]() | ![]() | |
![]() | ![]() | ![]() | |
![]() | ![]() | ||
![]() | ![]() | ![]() | ![]() |
![]() | |||
![]() | ![]() | ![]() | |
| cdn77 | ![]() | ||
![]() | ![]() | ||
![]() |
made by gramk, plays hls from address bar and m3u8 links
HLS.js is released under Apache 2.0 License