@gumlet/react-hls-player

中文文档
3.0.0发布于 2026/10/27MITTypeScriptCommonJS构建来源已验证近 30 天下载 7293

React component for HLS and DASH playback using Shaka Player, with Gumlet Widevine and FairPlay

原始使用文档
文档目录9 节
  1. Demo
  2. Basic playback
  3. Callbacks
  4. Video element and Shaka instance
  5. DRM
  6. Insights
  7. Playback settings
  8. Props
  9. Maintainer

@gumlet/react-hls-player

npm version npm downloads

React component for HLS and DASH live and VOD. Playback uses Shaka Player 5.1 with the same ABR, retry, and buffering settings as the Gumlet embed player. Widevine and FairPlay use Gumlet's license helpers.

npm i @gumlet/react-hls-player

Requires React 18+. Depends on shaka-player 5.1.

Version 3 replaces hls.js. hlsConfig, getHLSRef, and preferNativeHls are gone. Use playerConfig, getPlayerRef, and drm instead.

Demo

npm start

Opens the example on port 8000. It plays a sample Gumlet playlist and writes every callback into an event log under the video. onTimeUpdate and onProgress are sampled so the log stays readable.

  • Load, or Enter in the stream URL field, applies the URL and any Widevine or FairPlay URIs and mounts the player. Use it again after Destroy Video.
  • Checkboxes toggle muted, autoPlay, and startHighestRes.
  • Leave the DRM fields blank for clear playback.

Basic playback

import React from 'react';
import { createRoot } from 'react-dom/client';
import ReactHlsPlayer from '@gumlet/react-hls-player';

createRoot(document.getElementById('app')).render(
  <ReactHlsPlayer
    src="https://video.gumlet.io/5f462c1561cf8a766464ffc4/635789f017629894d4d125a4/main.m3u8"
    autoPlay={false}
    muted
    controls
    playsInline
    loop
    width="100%"
    height="auto"
  />
);

Shaka loads src. The path must be /{collection_id}/{asset_id}/main.m3u8 or main.mpd on any host. A missing collection id or asset id is reported with onError and thrown before Shaka is created. The URL is not set on the <video> element. autoPlay calls play() after load() resolves. Pair it with muted when the browser blocks autoplay with sound. loop, playsInline, poster, preload, crossOrigin, width, and height are normal video attributes.

Changing muted or autoPlay updates the element without creating a new Shaka instance. Changing src or drm does.

Callbacks

Pass on* props instead of listeners on the video element. A new function identity on each render does not rebuild the player.

import React, { useState } from 'react';
import ReactHlsPlayer from '@gumlet/react-hls-player';

function PlayerWithLog({ src }) {
  const [log, setLog] = useState([]);

  function append(name, payload) {
    setLog((rows) => [
      ...rows,
      payload == null ? name : `${name} ${JSON.stringify(payload)}`,
    ]);
  }

  return (
    <>
      <ReactHlsPlayer
        src={src}
        controls
        muted
        playsInline
        onReady={() => append('onReady')}
        onPlay={() => append('onPlay')}
        onPause={() => append('onPause')}
        onPlaying={() => append('onPlaying')}
        onEnded={() => append('onEnded')}
        onWaiting={() => append('onWaiting')}
        onTimeUpdate={({ currentTime, duration }) =>
          append('onTimeUpdate', { currentTime, duration })
        }
        onProgress={({ percent }) => append('onProgress', { percent })}
        onSeeked={({ currentTime, duration }) =>
          append('onSeeked', { currentTime, duration })
        }
        onVolumeChange={({ volume, muted }) =>
          append('onVolumeChange', { volume, muted })
        }
        onManifestParsed={() => append('onManifestParsed')}
        onQualityChange={({ level, height, bitrate }) =>
          append('onQualityChange', { level, height, bitrate })
        }
        onError={(error) => append('onError', error)}
      />
      <pre>{log.join('\n')}</pre>
    </>
  );
}

onReady and onManifestParsed both fire when player.load() resolves. onQualityChange runs on Shaka adaptation; bitrate is the active variant's bandwidth. onError reports Shaka errors (source: 'shaka') and media-element errors (source: 'video').

Video element and Shaka instance

PropWhat you get
playerRef / refThe <video> element (play(), pause(), currentTime)
getPlayerRefThe Shaka Player. Called with null when that instance is destroyed.

playerRef is optional. The component keeps an internal ref when you omit it. The active player is also window.shaka and window.shakaPlayer.

import React from 'react';
import ReactHlsPlayer from '@gumlet/react-hls-player';

function MyCustomComponent() {
  const playerRef = React.useRef(null);

  return (
    <ReactHlsPlayer
      playerRef={playerRef}
      getPlayerRef={(player) => {
        if (player == null) {
          return;
        }
      }}
      src="https://video.gumlet.io/5f462c1561cf8a766464ffc4/635789f017629894d4d125a4/main.m3u8"
      controls
    />
  );
}

DRM

FairPlay is used when both fairplayLicenseUri and fairplayCertificateUri are set. Playback stays on Shaka MSE (streaming.useNativeHlsForFairPlay: false). License requests are JSON { spc } and responses are JSON { ckc }.

Otherwise widevineLicenseUri configures com.widevine.alpha. widevineRobustness is L1, L2, custom, or omitted for the default ladder. organizationId and collectionId apply the same org overrides as the embed player.

<ReactHlsPlayer
  src={src}
  drm={{
    widevineLicenseUri: 'https://widevine.gumlet.com/licence/example',
    widevineRobustness: 'L1',
    organizationId: 'org-id',
    collectionId: 'collection-id',
    fairplayLicenseUri: 'https://fairplay.gumlet.com/licence/example',
    fairplayCertificateUri: 'https://fairplay.gumlet.com/certificate/example',
  }}
/>

When both FairPlay URIs are present, Widevine is not configured for that load.

Insights

Insights is on by default (enableInsights). Every playback URL is parsed before Shaka starts, including when insights are off. workspace_id is the collection id. customVideoId is the asset id unless you pass insights.customVideoId.

<ReactHlsPlayer
  src="https://video.gumlet.io/collection-id/asset-id/main.m3u8"
  insights={{
    property_id: 'property-id',
    customVideoTitle: 'Episode 3',
    customData1: 'experiment-a',
    userId: 'viewer-1',
  }}
/>

customPlayerName is gumlet-react-hls-player and customPlayerVersion is this package's version. Those cannot be overridden. workspace_id is not a prop.

insights accepts the fields @gumlet/insights-js-core still documents: property_id, debug, test, page_url, sessionID, userID, sendSessionRequest, deviceData, playerData, disable_analytics_v2, getUUID, customData1 through customData10, video fields (customVideoId, customVideoTitle, customVideoDurationMillis, customVideoSeries, customVideoProducer, customVideoLanguage, customVideoVariant, customVideoVariantName, customContentType, customEncodingVariant), user fields (userId, userName, userEMail or userEmail, userPhone, userProfileImage, address fields, userCity, userState, userCountry, userZipcode), plus customPageType and experimentName.

<ReactHlsPlayer src={src} enableInsights={false} />

Playback settings

Every load applies the embed player's Shaka settings:

  • ABR with a 3 Mbps default estimate and the network-information API off
  • Manifest retries: 6 attempts, 1s base delay, 30s timeout
  • Segment retries: 6 attempts, 500ms base delay, 20s timeout
  • rebufferingGoal: 4, bufferingGoal: 20
  • manifest.disableText and StubTextDisplayer, so Shaka does not take over native <track> captions

startHighestRes keeps ABR off while load() runs, then selects the tallest playable variant. A portrait aspectRatio such as 9:16 turns off restrictToElementSize.

playerConfig is an optional partial Shaka PlayerConfiguration. It is applied first. Embed settings and DRM are applied after it, so those values stay in effect.

<ReactHlsPlayer
  src={src}
  aspectRatio="16:9"
  startHighestRes
  playerConfig={{ streaming: { bufferingGoal: 30 } }}
/>

Fatal Shaka errors (severity CRITICAL) call load(src) again up to maxFatalRetries (default 3). DRM codes 6000–6010 and 3014–3016 are reported and not retried.

An .m3u8 URL loads shaka-player.hls.js. An .mpd URL loads shaka-player.dash.js. debug loads that build's debug file and sets its log level to DEBUG. Leave it off for the matching release build. This is separate from insights.debug.

<ReactHlsPlayer src={src} debug />

Props

Other video attributes pass through to <video>, except onPlay, onPause, onPlaying, onWaiting, onEnded, onError, onTimeUpdate, onProgress, onSeeked, and onVolumeChange. Those are the typed callbacks above.

PropDescription
src string, required/{collection_id}/{asset_id}/main.m3u8 or main.mpd. Any host
autoPlay booleanCall play() after load() resolves. Default false
muted booleanMute the element before play()
controls booleanNative controls. Default false
loop, playsInline, poster, preload, crossOrigin, width, heightPassed through to <video>
playerConfigPartial Shaka config, applied before embed settings
playerRefRef to the <video> element (same node as ref)
refThe <video> element
getPlayerRef(player: shaka.Player | null) => void
aspectRatio stringPortrait W:H or W/H disables ABR restrictToElementSize
startHighestRes booleanABR off through load(), then lock the tallest variant
drmDrmConfig: Widevine and FairPlay fields
enableInsights booleanStart Gumlet Insights after the URL is parsed. Default true
insightsDocumented Insights fields. Workspace id and player name/version are set by this package
debug booleanLoad the debug file for this manifest and set Shaka's log level to DEBUG. Default false
maxFatalRetries numberFatal retries before giving up. Default 3
onReadyload() resolved
onPlay, onPause, onPlaying, onEnded, onWaitingVideo playback state
onTimeUpdate{ currentTime, duration }
onProgress{ percent } from currentTime / duration
onSeeked{ currentTime, duration }
onVolumeChange{ volume, muted }
onManifestParsedFires with onReady when load() resolves
onQualityChange{ level, height, bitrate } after adaptation
onError{ fatal, source, data?, mediaError?, message? }

Exported types: HlsPlayerProps, DrmConfig, InsightsConfig, AnalyticsConfig, PlayerConfig, TimeEventData, ProgressEventData, VolumeEventData, QualityChangeData, PlayerErrorData.

Maintainer

This library is maintained by Gumlet.com

版本与发布记录

@gumlet/react-hls-player 共发布 5 个版本,首次发布于 2022/11/19;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.0latest2026/10/2720 天前
2.0.12026/10/2027 天前
2.0.02026/09/281 个月前
1.0.12022/11/233 年前
1.0.02022/11/193 年前

关于 @gumlet/react-hls-player 的常见问题

@gumlet/react-hls-player 是什么?

React component for HLS and DASH playback using Shaka Player, with Gumlet Widevine and FairPlay

如何安装 @gumlet/react-hls-player?

在项目目录运行 npm install @gumlet/react-hls-player,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=18)、react-dom(>=18)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gumlet/react-hls-player 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gumlet/react-hls-player 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@gumlet/react-hls-player 可以商用吗?

@gumlet/react-hls-player 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gumlet/react-hls-player 的下载量有多少?

根据 npm 官方下载统计,@gumlet/react-hls-player 在 2026/10/17 – 2026/11/15 这 30 天内被下载 7,293 次,日均约 243 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gumlet/react-hls-player 还在维护吗?

最新版本 3.0.0 发布于 2026/10/27(20 天前);至今共发布 5 个版本,其中过去 12 个月发布了 3 个;首次发布于 2022/11/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。