# mux-audio

Audio element for Mux-hosted HLS streams

Audio element for playing Mux-hosted HLS streams.

## Import

```bash
pnpm add @videojs/mux-audio
```

```ts
import '@videojs/html/media/mux-audio';
```

Or load it from the [CDN](../../guides/cdn.md):

```html
<script type="module" src="https://cdn.jsdelivr.net/npm/@videojs/cdn@10.6.0/media/mux-audio.js"></script>
```

## Choose a playback engine

The Mux audio component can play your audio through one of two engines: SPF or hls.js. An engine is the code that downloads the stream and feeds it to the browser. You choose one by its import path.

SPF is Video.js’s own engine, built for the streams Mux delivers. It’s a fraction of hls.js’s size, and it will become the default in an upcoming release. hls.js is mature, widely used, and plays almost any HLS stream. The default import uses hls.js today.

| Import | Engine | Choose it when |
| --- | --- | --- |
| `.../media/mux-audio/spf` | SPF | None of the cases under “When to use hls.js” applies to you. |
| `.../media/mux-audio` | hls.js today, SPF soon | You want the recommended engine, and you’re fine with it changing in a future release. |
| `.../media/mux-audio/hls-js` | hls.js | One of the cases under “When to use hls.js” applies to you. |

```ts
import '@videojs/html/media/mux-audio/spf';
```

All three imports register the same `<mux-audio>` tag with the same basic API. Load only one of them on a page: the first one to load claims the tag, and the others are ignored.

### When to use SPF

- **You want a smaller page.** SPF is about a quarter of hls.js’s size, which matters most with several players on a page or on slower connections.
- **You only need the audio.** SPF downloads only the audio, even when the Mux asset has video. hls.js downloads the video too, though no one sees it.
- **You use AirPlay.** Starting and stopping AirPlay works smoothly on SPF. hls.js can get into a bad state when you do either.

### When to use hls.js

SPF is still under development. Use hls.js if any of these applies to you:

- **You stream live without slates.** A slate is the image Mux shows while a broadcaster reconnects. Without one, playback stops at the point where the broadcaster dropped and came back, in the live stream and in the recording Mux makes of it.
- **You rely on detailed Mux Data.** With SPF, Mux Data doesn’t receive playback errors, or detail like quality switches and download speed.
- **You need low latency.** SPF plays low-latency live streams with the delay of an ordinary live stream.
- **You support older iPhones.** SPF needs iOS 17.1 or later.

### SPF limitations in detail

**Live streams without slates.** When an encoder disconnects, Mux keeps the live stream open for its `reconnect_window`. With a slate, Mux fills that time with the slate image, so the stream stays continuous. Without one, no media arrives until the encoder reconnects, and Mux marks the break with `EXT-X-DISCONTINUITY`. The asset Mux records from the stream keeps the same discontinuity. SPF doesn’t handle discontinuities yet, in CMAF or MPEG-TS, so playback breaks there. To avoid it, set `reconnect_window` above 0 and, for standard-latency streams, `use_slate_for_standard_latency` to `true`. [Handle live stream disconnects](https://www.mux.com/docs/guides/handle-live-stream-disconnects?utm_source=videojs&utm_campaign=vjs10&utm_content=docs-content) covers the settings.

**Mux Data.** Mux Data plugs into hls.js to collect engine-level data. It has no such integration for SPF, so it monitors the media element alone. Views, startup time, and rebuffering still come through. Errors SPF raises itself, such as a manifest that fails to load or content it can’t play, don’t, and neither do rendition switches or request timing and throughput.

**Low-Latency HLS.** SPF skips the partial segments (`EXT-X-PART`) that make LL-HLS low latency and loads whole segments instead. The stream plays as standard-latency live, at the distance from the live edge that the playlist’s `HOLD-BACK` sets. SPF logs a console warning when this happens.

**Browsers without Media Source Extensions.** SPF plays through `MediaSource`, or `ManagedMediaSource` on iPhone, and has no fallback to the browser’s own HLS playback. iPhone Safari before iOS 17.1 has neither, so SPF can’t play there. The hls.js flavor falls back to native HLS.

## Load a source

`<mux-audio>` takes Mux content two ways: a stream URL through `src`, or a structured `source` object.

```html
<mux-audio src="https://stream.mux.com/BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM.m3u8"></mux-audio>
```

The `source` object builds the URL for you from a playback ID, an optional custom domain, and `playback` params. Playback params are camelCased [Mux playback query params](https://www.mux.com/docs/api-reference/stream/streaming/get-hls-manifest?utm_source=videojs&utm_campaign=vjs10&utm_content=docs-content); for example, `max_resolution` becomes `maxResolution`.

```ts
const audio = document.querySelector('mux-audio')!;
audio.source = {
  playbackId: 'BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM',
  customDomain: 'media.example.com',
};
```

`<mux-audio>` ignores the same source object when it is assigned again. A new object fires `sourcechange` even when its values are equal, although an equivalent playback source does not reload.

## Signed playback

For [signed playback](https://www.mux.com/docs/guides/secure-video-playback?utm_source=videojs&utm_campaign=vjs10&utm_content=docs-content), put the playback token on `source.playback.token`. The token replaces every other playback param, so bake modifiers like time bounds into the token when you sign it.

```ts
const audio = document.querySelector('mux-audio')!;
audio.source = {
  playbackId: 'BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM',
  playback: { token: playbackToken },
};
```

## Analytics and casting

The Mux audio component plays Mux streams. It doesn’t monitor them or cast them — [Mux Data](../../guides/mux-data.md) and [Google Cast](../../guides/casting.md) are separate extensions you add to the player alongside it. Mux Data needs no environment key here, since Mux attributes the views to the environment that owns the playback ID:

Install both extensions before using the example below:

```bash
pnpm add @videojs/mux-data @videojs/google-cast
```

```html
<mux-audio src="https://stream.mux.com/BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM.m3u8"></mux-audio>
<mux-data player-software-name="mux-audio"></mux-data>
<google-cast></google-cast>
```

Register the elements by importing `@videojs/html/extensions/mux-data` and `@videojs/html/extensions/google-cast`.

- [Mux Data — metadata, options, and configuration](../../guides/mux-data.md)
- [Cast to AirPlay and Chromecast](../../guides/casting.md)

## Examples

### Basic Usage

**index.html**

```html
<mux-audio class="mux-audio" src="https://stream.mux.com/BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM.m3u8" crossorigin="anonymous" controls></mux-audio>
```

**index.css**

```css
.mux-audio {
  width: 100%;
  height: 54px;
}
```

**index.ts**

```ts
import '@videojs/html/media/mux-audio';
```

## API Reference

### Attributes

Forwards these standard media attributes to the internal `<audio>`. See the [MDN media element reference](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio): `autopictureinpicture`, `autoplay`, `controls`, `controlslist`, `crossorigin`, `disablepictureinpicture`, `disableremoteplayback`, `loading`, `loop`, `muted`, `playsinline`, `poster`, `preload`, `src`.

These Video.js-specific attributes configure media behavior:

| Attribute | Type | Default | Description |
| --- | --- | --- | --- |
| `stream-type` | `'on-demand' \| 'live' \| 'unknown'` | `'unknown'` | Current stream type (`'on-demand'` / `'live'` / `'unknown'`). |

### Properties

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `audioRenditions` | `AudioRenditionListLike \| undefined` | — | Read-only. Selectable audio variants, populated only while the hls.js (MSE) engine is active; otherwise `undefined`. |
| `audioTracks` | `AudioTrackListLike \| undefined` | — | Read-only. Populated only while the hls.js (MSE) engine is active; otherwise `undefined`. |
| `contentData` | `{ readonly [key: string]: MediaContentValue; title?: string; poster?: string; storyboard?: string }` | — | Read-only. What `source` says about its content. `poster` and `storyboard` are image URLs it describes rather than plays, from its `poster` and `storyboard` params; a key is absent when the URL can't be built — no playback ID, or signed playback without a matching image token. `title` and the rest come from the metadata Mux publishes for the asset, which loads with the source, so they arrive later than the URLs and are absent until then. The same object is handed back until something in it changes, and `contentdatachange` announces it when it does. Nothing here is applied for you, apart from the thumbnail track `<mux-video>` adds from `storyboard` (and drops for live streams). |
| `disableRemotePlayback` | `unknown` | `false` | Whether remote playback (AirPlay, Google Cast) is disabled for this media. |
| `engine` | `Hls \| null` | — | Read-only. Underlying playback engine — the hls.js `Hls` instance when playing via MSE, otherwise `null`. An advanced escape hatch for direct engine access; normal playback is driven through this element's own properties and methods. |
| `engineName` | `string \| undefined` | — | Read-only. Engine this media is playing through, reported to analytics such as Mux Data: `hlsjs` via MSE, `browser` for native HLS, or `undefined` until a source loads. Read from the instance because the engine is picked per source. |
| `error` | `MediaError \| null` | — | Read-only. |
| `liveEdgeStart` | `number` | — | Read-only. Presentation time marking the start of the Live Edge Window. Derived from the delegate on every read; `NaN` when no delegate is attached or the stream is not live. |
| `preload` | `MediaPreloadType` | `'metadata'` | Preload type (`'none'` / `'metadata'` / `'auto'`). |
| `source` | `{ type?: 'application/vnd.apple.mpegurl' \| 'video/mp4' \| string & {}; preferPlayback?: 'mse' \| 'native' \| string & {}; maxAutoResolution?: '270p' \| '360p' \| '480p' \| '540p' \| '720p' \| '1080p' \| '1440p' \| '2160p'; capRenditionToPlayerSize?: boolean; minAutoResolution?: '270p' \| '360p' \| '480p' \| '540p' \| '720p' \| '1080p' \| '1440p' \| '2160p'; engine?: HlsEngineConfig; src?: string; playbackId?: string; customDomain?: string; playback?: MuxPlaybackParams; poster?: MuxPosterParams; storyboard?: MuxStoryboardParams; drm?: MuxDrmParams } \| null` | `null` | Structured Mux source. Setting it derives `src` from the playback ID, custom domain, and `playback` params (appended as `snake_case` query params). A `playback.token` replaces all other params — signed URLs bake them into the token. Engine options live under `engine`. A `drm.token` fills in `drm` itself: Mux's FairPlay, Widevine, and PlayReady license servers for this playback ID, so protected media plays whichever path the browser takes. License servers named alongside the token win, key by key, for content Mux does not license. `playback.maxResolution` and `playback.minResolution` are server-side: they decide which renditions Mux puts in the manifest at all. The inherited `maxAutoResolution` and `minAutoResolution` only look like their pair — those are client-side and bound which of the renditions that *do* arrive adaptive selection reaches for. The two halves are independent. |
| `src` | `string` | `''` | Media source URL. Setting a Mux stream URL (`https://stream.mux.com/<playback-id>.m3u8?...`, with or without the `.m3u8` extension) extracts the playback ID and query params into `source`; other URLs are kept as a plain `source.src`. Only playback options carry over. Mux identity comes from the URL, and the signed `poster`, `storyboard`, and `drm` tokens are scoped to a playback ID, so carrying them onto a different source would build rejected URLs. |
| `streamType` | `'on-demand' \| 'live' \| 'unknown'` | `'unknown'` | Current stream type (`'on-demand'` / `'live'` / `'unknown'`). |
| `targetLiveWindow` | `number` | — | Read-only. Seekable range size for live content. `0` for standard live, `Infinity` for DVR, `NaN` for on-demand or unknown. Fires `targetlivewindowchange` when the value changes (bridged from the delegate). |
| `videoRenditions` | `VideoRenditionListLike \| undefined` | — | Read-only. Selectable quality levels, populated only while the hls.js (MSE) engine is active; otherwise `undefined`. |
| `videoTracks` | `VideoTrackListLike \| undefined` | — | Read-only. Populated only while the hls.js (MSE) engine is active; otherwise `undefined`. |

Also exposes these properties from the native media API. See [HTMLAudioElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement) for details: `autoplay`, `buffered`, `controls`, `crossOrigin`, `currentSrc`, `currentTime`, `defaultMuted`, `defaultPlaybackRate`, `duration`, `ended`, `loop`, `muted`, `paused`, `playbackRate`, `played`, `readyState`, `remote`, `seekable`, `seeking`, `textTracks`, `title`, `volume`.

### Engine options

#### `source.engine.nativeHls`

Options passed under `source.engine.nativeHls`.

| Option | Type | Description |
| --- | --- | --- |
| `drmSystems` | `Partial<Record<KeySystem, DrmSystemConfig>> \| undefined` | License servers for protected content, keyed by EME key system id. An escape hatch for licensing native playback differently from every other path: naming it replaces `source.drm` here, and nowhere else. |

### Methods

Supports these media methods. See [HTMLAudioElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement) for details: `addTextTrack`, `canPlayType`, `load`, `pause`, `play`, `removeTextTrack`.

### Events

Re-dispatches these standard media events from the internal media element: `abort`, `addtrack`, `canplay`, `canplaythrough`, `change`, `durationchange`, `emptied`, `ended`, `error`, `loadeddata`, `loadedmetadata`, `loadstart`, `pause`, `play`, `playing`, `progress`, `ratechange`, `removetrack`, `seeked`, `seeking`, `stalled`, `suspend`, `timeupdate`, `volumechange`, `waiting`.

Also emits these Video.js-specific events:

| Event | Description |
| --- | --- |
| `contentdatachange` | Fired when `contentData` changes: the derived URLs with `source`, and the metadata once it loads. Read `contentData` for the new value. |
| `sourcechange` | Fired when `source` changes, either directly or by resolving a new `src`. Read `source` for the new value. |
| `streamtypechange` | Fired when the detected stream type changes. Read `streamType` for the new value. |
| `targetlivewindowchange` | Fired when the target live window changes. Read `targetLiveWindow` for the new value. |