# @100mslive/hls-player 中文文档

规范地址：https://npmcn.com/package/%40100mslive/hls-player/

版本：0\.6\.3
npm 元数据更新时间：2026-09-30T17:35:46.008Z
中文译文更新时间：2026-11-05T20:24:27.710Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40100mslive/hls-player
原文对照：https://npmcn.com/package/%40100mslive/hls-player/?lang=original
项目主页：https://github.com/100mslive/web-sdks#readme
源码仓库：https://github.com/100mslive/web-sdks

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：125 kB，18 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：3 个
- 首次发布：2023-03-28T15:54:24.862Z
- 最新版本发布：2026-09-30T17:35:45.613Z
- 近 30 天下载量：29006（2026-10-04 至 2026-11-02，npm 官方下载统计）
- 已发布版本数：506（近 12 个月 81 个）

## 中文简介

HLS 客户端库, 使用 HTML5 视频元素和媒体源扩展来回播放

## 安装

```sh
npm install @100mslive/hls-player
```

也可以使用：`pnpm add @100mslive/hls-player`、`yarn add @100mslive/hls-player`、`bun add @100mslive/hls-player`

## README

# 100ms HLS 播放器

[![Lint, Test and Build](https://github.com/100mslive/web-sdks/actions/workflows/lint-test-build.yml/badge.svg)](https://github.com/100mslive/web-sdks/actions/workflows/lint-test-build.yml) [![Bundle Size](https://badgen.net/bundlephobia/minzip/@100mslive/hls-player)](https://bundlephobia.com/result?p=@100mslive/hls-player) [![License](https://img.shields.io/npm/l/@100mslive/hls-player)](https://www.100ms.live/) ![Tree shaking](https://badgen.net/bundlephobia/tree-shaking/@100mslive/hls-player)

这个 `HMSHLSPlayer` 是一款由100ms提供的HLS播放器,可用于播放HLS流. 玩家使用URL和视频元素来播放流.

## 如何整合 HLS 播放器 SDK

您可以使用节点包管理器或纱线将 HMSHLSPlayer sdk 添加到您的工程中. 使用 [@ 100mslive/hls- player (英语)](https://www.npmjs.com/package/@100mslive/hls-player) 作为软件包源.

```bash
npm i @100mslive/hls-player
```

## HMSHLSP 制定方法

下面显示玩家曝光的所有方法

```javascript
interface IHMSHLSPlayer {
  /**
   * @returns get html video element
   */
  getVideoElement(): HTMLVideoElement;

  /**
   * set video volumne
   * @param { volume } - in range [0,100]
   */
  setVolume(volume: number): void;
  /**
   *
   * @returns returns HMSHLSLayer which represents current
   * quality.
   */
  getLayer(): HMSHLSLayer | null;
  /**
   *
   * @param { HMSHLSLayer } layer - layer we want to set the stream to.
   * set { height: auto } to set the layer to auto
   */
  setLayer(layer: HMSHLSLayer): void;
  /**
   * move the video to Live
   */
  seekToLivePosition(): Promise<void>;
  /**
   * play stream
   * call this when autoplay error is received
   */
  play(): Promise<void>;
  /**
   * pause stream
   */
  pause(): void;

  /**
   * It will update the video element current time
   * @param seekValue Pass currentTime in second
   */
  seekTo(seekValue: number): void;
}
```

### 如何使用玩家的 HLS 流

您创建 HMSHLSPlayer 实例如下 :

```javascript
import { HMSHLSPlayer } from '@100mslive/hls-player';

// hls url should be provided which player will run.
// second parameter is optional, if you had video element then pass to player else we will create one.
const hlsPlayer = new HMSHLSPlayer(hlsURL, videoEl)

// if video element is not present, we will create a new video element which can be attached to your ui.
const videoEl = hlsPlayer.getVideoElement();
```

### 如何暂停并恢复播放

您在 HlsPlayer 实例上调用播放/暂停如下 :

```javascript
// return Promise<void>
hmsPlayer.play()

hmsPlayer.pause()
```

### 如何向前或向后寻找

你用这个 `seekTo` 以下举例说明hlsPlayer上寻求任何视频位置的方法:

```javascript
// seekValue Pass currentTime in second
hmsPlayer.seekTo(5)
```

### 如何寻求生存

你用这个 `seekToLivePosition` 在hlsPlayer实例上使用如下方法进行活页:

```javascript
hmsPlayer.seekToLivePosition()
```

### 如何改变 HLS 播放的音量

使用音量属性来更改 HLS 播放器的音量 。 音量级别为0-100. 音量默认为100.

```javascript
hlsPlayer.setVolume(50);
```

### 将视频质量级别设定为 Hls 播放器

```javascript
/**
*
* @returns returns HMSHLSLayer which represents current
* quality.
*/
hlsPlayer.getLayer(): HMSHLSLayer | null;
/**
*
* @param { HMSHLSLayer } layer - layer we want to set the stream to.
* set { height: auto } to set the layer to auto
*/
hlsPlayer.setLayer(layer: HMSHLSLayer): void;

// quality interface
interface HMSHLSLayer {
  readonly bitrate: number;
  readonly height?: number;
  readonly id?: number;
  readonly width?: number;
  url: string;
  resolution?: string;
}
```

## 从 HMSHLSP 显示器曝光的事件

我们正在揭露我们玩家的事件.

```javascript
enum HMSHLSPlayerEvents {
  TIMED_METADATA_LOADED = 'timed-metadata',
  SEEK_POS_BEHIND_LIVE_EDGE = 'seek-pos-behind-live-edge',

  CURRENT_TIME = 'current-time',
  AUTOPLAY_BLOCKED = 'autoplay-blocked',

  MANIFEST_LOADED = 'manifest-loaded',
  LAYER_UPDATED = 'layer-updated',

  ERROR = 'error',
  PLAYBACK_STATE = 'playback-state',
  STATS = 'stats',
}
```

### 回放状态

```javascript
enum HLSPlaybackState {
  playing,
  paused,
}
interface HMSHLSPlaybackState {
  state: HLSPlaybackState;
}
hlsPlayer.on(HMSHLSPlayerEvents.PLAYBACK_STATE, (event: HMSHLSPlayerEvents, data: HMSHLSPlaybackState): void => {});
```

### HLS 点数

```javascript
interface HlsPlayerStats {
    /** Estimated bandwidth in bits/sec. Could be used to show connection speed. */
    bandwidthEstimate?: number;
    /** The bitrate of the current level that is playing. Given in bits/sec */
    bitrate?: number;
    /** the amount of video available in forward buffer. Given in ms */
    bufferedDuration?: number;
    /** how far is the current playback from live edge.*/
    distanceFromLive?: number;
    /** total Frames dropped since started watching the stream. */
    droppedFrames?: number;
    /** the m3u8 url of the current level that is being played */
    url?: string;
    /** the resolution of the level of the video that is being played */
    videoSize?: {
        height: number;
        width: number;
    };
}

hlsPlayer.on(HMSHLSPlayerEvents.STATS, (event: HMSHLSPlayerEvents, data: HlsPlayerStats): void => {});
```

### 明确装入的数据

Hls 播放器将会提供一个表, 一旦装入url, 它将提供类似不同质量层的数据 .

```javascript
interface HMSHLSManifestLoaded {
  layers: HMSHLSLayer[];
}
hlsPlayer.on(HMSHLSPlayerEvents.MANIFEST_LOADED, (event: HMSHLSPlayerEvents, data: HMSHLSManifestLoaded): void => {});
```

### 质量变化数据

```javascript
interface HMSHLSLayerUpdated {
  layer: HMSHLSLayer;
}
hlsPlayer.on(HMSHLSPlayerEvents.LAYER_UPDATED, (event: HMSHLSPlayerEvents, data: HMSHLSLayerUpdated): void => {});
```

### 现场活动

玩家会告诉你玩家是否在直播视频

```javascript
interface HMSHLSStreamLive {
  isLive: boolean;
}
hlsPlayer.on(HMSHLSPlayerEvents.SEEK_POS_BEHIND_LIVE_EDGE, (event: HMSHLSPlayerEvents, data: HMSHLSStreamLive): void => {});
```

### HLS 计时元数据

HLS 播放器将解析并发送定时-元数据.

```javascript
interface HMSHLSCue {
  id?: string;
  payload: string;
  duration: number;
  startDate: Date;
  endDate?: Date;
}
hlsPlayer.on(HMSHLSPlayerEvents.TIMED_METADATA_LOADED, (event: HMSHLSPlayerEvents, data: HMSHLSCue): void => {});
```

### 处理错误

```javascript
interface HMSHLSException {
  name: string,
   message: string,
  description: string,
  isTerminal: boolean, // decide if player error will automatically restart(if false)
}
hlsPlayer.on(HMSHLSPlayerEvents.ERROR, (event: HMSHLSPlayerEvents, data: HMSHLSException): void => {});
hlsPlayer.on(HMSHLSPlayerEvents.AUTOPLAY_BLOCKED, (event: HMSHLSPlayerEvents, data: HMSHLSException): void => {});
```

### 当前时间

```javascript
hlsPlayer.on(HMSHLSPlayerEvents.CURRENT_TIME, (event: HMSHLSPlayerEvents, data: number): void => {});
```

### 事件使用示例

以下是如何使用hls玩家事件的例子

```javascript
const isPlaying = false;
const playbackEventHandler = data => isPlaying = data.state === HLSPlaybackState.paused;
hlsPlayer.on(HMSHLSPlayerEvents.PLAYBACK_STATE, playbackEventHandler);
```

## 高级 玩家示例

下面是一个简单的例子,其中hls-player将被用于您的应用中.

```javascript
// Vanilla JavaScript Example
import { HLSPlaybackState, HMSHLSPlayer, HMSHLSPlayerEvents } from "@100mslive/hls-player";

const videoEl; // reference for video element
const hlsUrl; // reference to hls url

// variable to handle ui and take some actions
let isLive = true, isPaused = false, isAutoBlockedPaused = false;

const handleError = data => console.error("[HLSView] error in hls", data);
const handleNoLongerLive = ({ isLive }) => isLive = isLive;

const playbackEventHandler = data => isPaused = (data.state === HLSPlaybackState.paused);

const handleAutoplayBlock = data => isAutoBlockedPaused = !!data;

const hlsPlayer = new HMSHLSPlayer(hlsUrl, videoEl);

hlsPlayer.on(HMSHLSPlayerEvents.SEEK_POS_BEHIND_LIVE_EDGE, handleNoLongerLive);
hlsPlayer.on(HMSHLSPlayerEvents.ERROR, handleError);
hlsPlayer.on(HMSHLSPlayerEvents.PLAYBACK_STATE, playbackEventHandler);
hlsPlayer.on(HMSHLSPlayerEvents.AUTOPLAY_BLOCKED, handleAutoplayBlock);
```

```jsx
// React Example
import { HLSPlaybackState, HMSHLSPlayer, HMSHLSPlayerEvents } from "@100mslive/hls-player";
import { useEffect, useState } from 'react';

const videoEl; // reference for video element
const hlsUrl; // reference to hls url

// variable to handle ui and take some actions
const [isVideoLive, setIsVideoLive] = useState(true);
const [isHlsAutoplayBlocked, setIsHlsAutoplayBlocked] = useState(false);
const [isPaused, setIsPaused] = useState(false);

useEffect(() => {
    const handleError = data => console.error("[HLSView] error in hls", data);
    const handleNoLongerLive = ({ isLive }) => {
        setIsVideoLive(isLive);
    };

    const playbackEventHandler = data =>
        setIsPaused(data.state === HLSPlaybackState.paused);

    const handleAutoplayBlock = data => setIsHlsAutoplayBlocked(!!data);
    const hlsPlayer = new HMSHLSPlayer(hlsUrl, videoEl);

    hlsPlayer.on(HMSHLSPlayerEvents.SEEK_POS_BEHIND_LIVE_EDGE, handleNoLongerLive);
    hlsPlayer.on(HMSHLSPlayerEvents.ERROR, handleError);
    hlsPlayer.on(HMSHLSPlayerEvents.PLAYBACK_STATE, playbackEventHandler);
    hlsPlayer.on(HMSHLSPlayerEvents.AUTOPLAY_BLOCKED, handleAutoplayBlock);
    return () => {
        hlsPlayer.off(HMSHLSPlayerEvents.SEEK_POS_BEHIND_LIVE_EDGE, handleNoLongerLive);
        hlsPlayer.off(HMSHLSPlayerEvents.ERROR, handleError);
        hlsPlayer.off(HMSHLSPlayerEvents.PLAYBACK_STATE, playbackEventHandler);
        hlsPlayer.off(HMSHLSPlayerEvents.AUTOPLAY_BLOCKED, handleAutoplayBlock);
    }
}, []);

```

## 常见问题

### @100mslive/hls-player 是什么？

HLS 客户端库, 使用 HTML5 视频元素和媒体源扩展来回播放

### 如何安装 @100mslive/hls-player？

在项目目录运行 npm install @100mslive/hls-player，或使用 pnpm add / yarn add / bun add。

### @100mslive/hls-player 支持 TypeScript 吗？

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

### @100mslive/hls-player 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @100mslive/hls-player 可以商用吗？

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

### @100mslive/hls-player 的下载量有多少？

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

### @100mslive/hls-player 还在维护吗？

最新版本 0\.6\.3 发布于 2026/10/01（1 个月前）；至今共发布 506 个版本，其中过去 12 个月发布了 81 个；首次发布于 2023/03/28。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

