---
url: https://audiobrowser.dev/guide/getting-started.md
description: >-
Install react-native-audio-browser and its react-native-nitro-modules peer
dependency, complete the iOS and Android native setup, and add shaka-player if
you target the browser.
---
# Getting Started
## Installation
The library requires **React Native 0.76 or newer** (with the New Architecture enabled) and React 18.2+, and runs on iOS 16+ and Android API 24+. Building for iOS needs Xcode 26.4 or later (Swift 6.3): Swift 6.2 has a bug that makes the library crash on iOS below 18, so the library refuses to compile with it. `react-native-nitro-modules` 0.35 or later is a required peer dependency — install it alongside:
::: code-group
```bash [npm]
npm install react-native-audio-browser react-native-nitro-modules
```
```bash [yarn]
yarn add react-native-audio-browser react-native-nitro-modules
```
```bash [pnpm]
pnpm add react-native-audio-browser react-native-nitro-modules
```
```bash [bun]
bun add react-native-audio-browser react-native-nitro-modules
```
:::
On iOS, install the pods:
```bash
cd ios && pod install
```
For playback to continue in the background on iOS, add the `audio` background mode to your app's `Info.plist`:
```xml
UIBackgroundModes
audio
```
Android links automatically.
For web (`react-native-web`), also install [`shaka-player`](https://github.com/shaka-project/shaka-player) 4 (4.7.9 or later). It is an optional peer dependency that the web player loads during `setupPlayer()`. Native builds don't need it.
::: code-group
```bash [npm]
npm install shaka-player
```
```bash [yarn]
yarn add shaka-player
```
```bash [pnpm]
pnpm add shaka-player
```
```bash [bun]
bun add shaka-player
```
:::
## Basic Setup
```ts
import { setupPlayer } from 'react-native-audio-browser'
// Initialize the player once at startup
await setupPlayer()
```
> The library exposes both named exports (`import { setupPlayer }`) and a default namespace (`import AudioBrowser from '…'; AudioBrowser.setupPlayer()`). The guides use the named form throughout.
## Web
The same API runs in the browser. On web the library plays through an HTML `` element driven by [Shaka Player](https://github.com/shaka-project/shaka-player), the optional peer dependency from [Installation](#installation).
Your bundler must resolve `.web.ts` / `.web.js` files ahead of plain ones, as react-native-web setups do, and map `react-native` to `react-native-web`. On the server (no `window`) `setupPlayer()` creates no player, so call it in the browser.
Playback, the queue, browse, search and the sleep timer work as on native. Now Playing metadata goes to the browser's Media Session API, so the system's media controls, media keys and Bluetooth buttons show the track and drive the player through the same [remote controls](/guide/remote-controls) handlers.
What web lacks:
* No CarPlay or Android Auto: the [Gate](/guide/gate) does nothing and `isCarConnected()` is always `false`.
* The [equalizer](/guide/equalizer), [battery](/guide/battery) and [audio output](/guide/audio-output) APIs return their empty values (`undefined`, `false`, `'unrestricted'`) and their setters do nothing. `getSystemVolume()` is always `1` and `setSystemVolume()` does nothing.
* No automatic retry (manual `retry()` works) and no timed metadata, neither ICY nor HLS ID3; see [Live Streams](/guide/live-streams#dropouts-stalls-and-retry).
## Next Steps
* [Basic Usage](/guide/basic-usage) - Learn how to play audio and build navigation trees
* [Android Auto](/guide/android-auto) - Set up Android Auto integration
* [CarPlay](/guide/carplay) - Set up CarPlay integration
---
---
url: https://audiobrowser.dev/guide/basic-usage.md
description: >-
The browse tree in one page: browsable versus playable Tracks, setting up the
player, declaring content, and playing it.
---
# Basic Usage
This guide covers the core idea — the **browse tree** — and the minimal code to set up the player, define some content, and play it. Installation is in [Getting Started](/guide/getting-started).
## The browse tree
The library models all content as one navigable tree of **Tracks**. A Track is **browsable** or **playable**, depending on which field you set:
* **Browsable** — has a `path`; navigating into it resolves its children.
* **Playable** — has a `src`; the player can stream it.
Set exactly one. [Track → Browsable or playable](/guide/track#browsable-or-playable) covers a Track that sets both.
Three fields at a glance — each answers a different question about a Track:
| Field | Answers | Meaning |
| ------ | ------------------ | --------------------------------------------------------- |
| `path` | where does it go? | the browse-tree address navigating opens |
| `src` | what does it play? | the media identifier the player streams |
| `id` | which item is it? | identity across surfaces — falls back to `src` when unset |
```mermaid
graph TD
Root[Root]
Root --> Favorites[Favorites]
Root --> Recent[Recently Played]
Root --> Browse[Browse]
Browse --> Jazz[Jazz]
Browse --> Rock[Rock]
Jazz --> J1[Smooth Floret FM]
Jazz --> J2[The Stalk 88.5]
Rock --> R90[Vintage]
Rock --> R1[Crunchy Greens]
Rock --> R2[Stem City Radio]
R90 --> R3[Funky Floret 101.3]
R90 --> R4[Wilted Greens FM]
classDef browsable fill:#e3f2fd,stroke:#1976d2
classDef playable fill:#e8f5e9,stroke:#388e3c
class Root,Favorites,Recent,Browse,Jazz,Rock,R90 browsable
class J1,J2,R1,R2,R3,R4 playable
```
One tree powers both your in-app UI and the native browse views on CarPlay and Android Auto.
## Set up the player
Call `setupPlayer()` once at startup to initialize the player:
```ts
import { setupPlayer } from 'react-native-audio-browser'
await setupPlayer()
```
## Define a browse tree
Describe the tree with `configureBrowser`: **tabs** along the top, and **routes** that resolve each path to its children. The simplest source is static data declared inline:
```ts
import { configureBrowser } from 'react-native-audio-browser'
configureBrowser({
tabs: [{ title: 'Browse', path: '/browse' }],
routes: {
'/browse': {
path: '/browse',
title: 'Browse',
children: [
{
title: 'Jazz',
// A path makes this browsable — tapping it opens that path.
path: '/browse/jazz'
},
{
title: 'Smooth Floret FM',
// A src makes this playable — tapping it streams the track.
src: 'https://example.com/floret.mp3'
}
]
},
'/browse/jazz': {
path: '/browse/jazz',
title: 'Jazz',
children: [
{
title: 'The Stalk 88.5',
src: 'https://example.com/stalk.mp3'
}
]
}
}
})
```
A route value is a [`BrowserSource`](/api/types/browser/#browsersource): the static page object shown above, an **async callback** that returns one (`'/path': async ({ path, routeParams }) => ({ path, title, children })`), or an HTTP request config that fetches it from your API — handy for trees too large to declare upfront.
A page can also group its tracks into titled, styled **sections** (`sections: [{ title, style, children }, …]`) — a flat `children` list like the ones above is shorthand for a single untitled section. See [Browser → How a path resolves](/guide/browser#how-a-path-resolves).
## Play a track
On CarPlay and Android Auto, tapping a playable Track plays it for you. To drive playback from your own UI, set a queue and call `play`:
```ts
import { setQueue, play } from 'react-native-audio-browser'
setQueue([{ title: 'Smooth Floret FM', src: 'https://example.com/floret.mp3' }])
play()
```
## The queue
The player works through a **queue** of Tracks. The Track at the current position is the **active track** — it's what plays, and what external next/previous controls (car, headphones, lock screen) move between.
**Now Playing** is the metadata shown on the lock screen, notification, and car surfaces. By default it mirrors the active track; for live streams you can override it as the current song changes — see [Now Playing](/guide/now-playing).
## Read state in your UI
Reactive hooks keep your in-app UI in sync with playback — they re-render automatically as it changes:
```tsx
import { Button } from 'react-native'
import {
togglePlayback,
usePlayingState,
useActiveTrack
} from 'react-native-audio-browser'
function PlayPauseButton() {
const { playing } = usePlayingState()
const track = useActiveTrack()
return (
togglePlayback()}
/>
)
}
```
See the [API reference](/api/) for the full set of hooks (`useProgress`, `useQueue`, `useNowPlaying`, and more).
---
---
url: https://audiobrowser.dev/guide/configuration.md
description: >-
The whole options surface — setupPlayer, updateOptions, and getOptions —
mapped to the feature guide that covers each area in depth.
---
# Configuration
Everything about how the player behaves is set through three functions:
* [`setupPlayer(options?)`](/api/features/player/#setupplayer) — the one
declarative call that initializes the player, run once at startup.
* [`updateOptions(options)`](/api/features/player/#updateoptions) — change a
subset of options later, at runtime.
* [`getOptions()`](/api/features/player/#getoptions) /
[`useOptions()`](/api/features/player/#useoptions) — read the current
options.
This page maps the whole options surface and links to the feature guide that
covers each area in depth.
## `setupPlayer`
Call it once at startup. It's `async`, and applies all options atomically — the
player never exists without its configuration:
```ts
import { setupPlayer } from 'react-native-audio-browser'
await setupPlayer({
playWhenReady: true,
repeatMode: 'queue',
capabilities: { favorite: true },
progressUpdateEventInterval: 0.5,
android: { audioContentType: 'music' },
ios: { category: 'playback' }
})
```
Calling `setupPlayer` again is how you change a
[setup-only option](#setup-only-vs-updatable) after launch. The runtime options
(capabilities, intervals, the updatable `android` / `ios` fields) carry over on
both platforms. The setup-only fields behave differently on each:
* **Android** reconfigures in place. The fields you pass are merged over the
previous ones, and the audio engine is only rebuilt when a construction-bound
field (buffers, wake mode, …) changed. Two fields are exceptions. Left out,
`remoteOutputs` turns the remote outputs off again, and `nowPlaying` turns
the default mapping back on. A `nowPlaying` formatter stays until another
function replaces it: passing `true` or leaving it out does not drop it.
* **iOS** replaces the player, built from that call's options alone. The queue
is cleared, and a setup-only field you leave out (`ios.category`,
`ios.buffer`, `retry`, …) goes back to its default, so pass the full `ios` and
`retry` set each time.
## `updateOptions`
Use it to change runtime options after setup. Every field is optional — pass only
what changes; the values you provide are **merged** over the current ones.
```ts
import { updateOptions } from 'react-native-audio-browser'
updateOptions({ capabilities: { shuffleMode: false } })
updateOptions({ progressUpdateEventInterval: null }) // disable progress events
updateOptions({ ios: { carPlayNowPlayingButtons: ['repeat'] } })
```
`null` means something on two fields:
`progressUpdateEventInterval: null` disables progress events, and
`android.remoteButtonLayout: null` goes back to the layout derived from
capabilities. Elsewhere, omit a field to leave it unchanged.
## Setup-only vs updatable
`updateOptions` can change only a subset. The rest are set in `setupPlayer`
(call it again to change them later; on iOS that call also clears the queue and
resets any setup-only field you omit, see [`setupPlayer`](#setupplayer)).
| Option | `setupPlayer` | `updateOptions` |
| ------------------------------------------------------------------------------------------------------------ | :-----------: | :-------------: |
| `capabilities` | ✓ | ✓ |
| `forwardJumpInterval` / `backwardJumpInterval` | ✓ | ✓ |
| `progressUpdateEventInterval` | ✓ | ✓ |
| `android.appKilledPlaybackBehavior` / `skipSilence` / `remoteButtonLayout` | ✓ | ✓ |
| `ios.playbackRates` / `carPlayUpNextButton` / `carPlayNowPlayingButtons` / `carPlayPlayingIndicatorLocation` | ✓ | ✓ |
| `nowPlaying` (metadata formatter) | ✓ | — |
| `playWhenReady`, `repeatMode` (initial values) | ✓ | — |
| `retry`, `keepSessionAliveOnError`, `remoteOutputs` | ✓ | — |
| `android` / `ios` audio engine & session (`audioContentType`, `wakeMode`, `category`, …) | ✓ | — |
`remoteOutputs` (Android) turns on the outputs of the system Output Switcher
beyond the phone's own: `{}` lists media route providers' speakers, and
`{ cast: true, sonos: true }` plays on Cast devices and Sonos rooms. Left out of
a `setupPlayer` call, they are off; see
[Remote outputs](/guide/audio-output#remote-outputs-android).
`retry` retries load errors automatically, and is off by default; see
[Automatic retry](/guide/errors#automatic-retry). `keepSessionAliveOnError`
(Android, default `true`) keeps the media session and its transport controls
through a terminal playback error, so Android Auto keeps next and previous on a
dead stream.
`playWhenReady` and `repeatMode` set the *initial* state; change them at runtime
with [`setPlayWhenReady`](/guide/playback#play-when-ready) /
[`setRepeatMode`](/guide/queue#repeat-and-shuffle), not `updateOptions`.
## Capabilities
`capabilities` controls which transport controls the system surfaces (lock
screen, notification, CarPlay, Android Auto) expose. **All default to `true`
except `jumpForward`, `jumpBackward`, and `favorite`, which default to `false`.**
Capabilities **merge** — list only the ones you want to change, and the rest keep
their current value:
```ts
updateOptions({
capabilities: { jumpForward: true, jumpBackward: true } // podcast controls
})
```
| Capability | Default | Notes |
| ------------------------------- | ------- | ---------------------------------------------- |
| `play` / `pause` / `stop` | `true` | Core transport. |
| `seekTo` | `true` | Scrub the timeline. |
| `skipToNext` / `skipToPrevious` | `true` | Move between queue items. |
| `jumpForward` / `jumpBackward` | `false` | Podcast/audiobook seek by interval. |
| `playbackRate` | `true` | Speed control (Control Center / CarPlay). |
| `shuffleMode` / `repeatMode` | `true` | Shuffle / repeat toggles. |
| `favorite` | `false` | The heart — see [Favorites](/guide/favorites). |
## Controls & progress
| Option | Default | What |
| ----------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `forwardJumpInterval` | `15` | Seconds for the jump-forward control. With no handler, Android seeks by Media3's fixed increment instead; see [Remote Controls](/guide/remote-controls#overriding-a-control). |
| `backwardJumpInterval` | `15` | Seconds for the jump-backward control. With no handler, Android seeks by Media3's fixed increment instead; see [Remote Controls](/guide/remote-controls#overriding-a-control). |
| `progressUpdateEventInterval` | `null` | Seconds between progress events; `null` disables them — see [Playback → Progress](/guide/playback#progress). |
## Now Playing
`nowPlaying` controls what's published to the now-playing surfaces:
* `true` (default) — publish the track's own title / artist.
* `false` — don't manage now-playing metadata.
* a formatter callback — render every line yourself.
It's **setup-only** (a function can't cross `updateOptions`). See
[Now Playing → the formatter](/guide/now-playing#the-formatter-derived-continuous).
## Android options (`android`)
| Option | Default | What |
| --------------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `appKilledPlaybackBehavior` | `'stop-playback-and-remove-notification'` | What happens when the app is swiped away (`continue-playback` / `pause-playback` / `stop-playback-and-remove-notification`). |
| `skipSilence` | `false` | Skip silent segments during playback. |
| `remoteButtonLayout` | `null` | Explicit button placement (`back` / `forward` / `overflow`); `null` derives it from capabilities — see [Button layout](/guide/remote-controls#button-layout-android). |
| `audioContentType` | `'music'` | Audio attributes content type (setup-only). |
| `wakeMode` | `'none'` | CPU/network wake lock during playback (setup-only). |
| `handleAudioBecomingNoisy` | `true` | Pause when the audio becomes noisy, such as when headphones are unplugged (setup-only). |
| `maxBuffer` | `50000` | Milliseconds of media the player loads ahead (setup-only). |
| `minBuffer` | `50000` | Accepted but has no effect; the player always loads up to `maxBuffer` (setup-only). |
| `playBuffer` | `1000` | Milliseconds that must be buffered to start or resume after a user action such as a seek (setup-only). |
| `rebufferBuffer` | `null` | Milliseconds that must be buffered to resume after a rebuffer; `null` adapts it to how fast the buffer drained (setup-only). |
| `backBuffer` | `0` | Milliseconds kept behind the playhead (setup-only). |
| `maxCacheSize` | `0` | Cache size in MB (setup-only). |
| `audioOffload` | `false` | Decode on dedicated hardware to save power (setup-only). |
## iOS options (`ios`)
| Option | Default | What |
| --------------------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `playbackRates` | `[0.5, 1.0, 1.5, 2.0]` | Rates offered by the rate control. |
| `carPlayUpNextButton` | `true` | Show the "Up Next" button on CarPlay (auto-hidden when the queue has one track). |
| `carPlayNowPlayingButtons` | `[]` | Buttons on the CarPlay now-playing screen, left to right, at most one of each kind: see [CarPlay](/guide/carplay#now-playing-buttons). |
| `carPlayPlayingIndicatorLocation` | `'leading'` | Where the now-playing indicator draws on CarPlay list rows: `'leading'` in the artwork slot, `'trailing'` at the end of the row — see [CarPlay](/guide/carplay#playing-indicator). |
| `category` | `'playback'` | iOS audio session category (setup-only). |
| `categoryMode` | `'default'` | Audio session mode (setup-only). |
| `categoryOptions` | `[]` | Audio session category options (setup-only). |
| `categoryPolicy` | `'default'` | Audio session route-sharing policy (setup-only). |
| `buffer` | `0` | Preferred forward buffer in milliseconds; `0` lets AVPlayer choose (setup-only). |
## Reading the current options
[`getOptions()`](/api/features/player/#getoptions) returns the current
[`Options`](/api/features/player/#options) (capabilities, intervals,
`progressUpdateEventInterval`, and the `android` / `ios` blocks for the current
platform). `capabilities` holds only the capabilities you set, plus
`jumpForward` / `jumpBackward: false` on Android and iOS. A missing entry means
its default from the [Capabilities](#capabilities) table, so test
`capabilities.play !== false` rather than `capabilities.play === true`.
[`useOptions()`](/api/features/player/#useoptions) is the reactive hook;
[`onOptionsChanged`](/api/features/player/#onoptionschanged) is the
subscription.
```tsx
import { useOptions } from 'react-native-audio-browser'
function JumpInterval() {
const { forwardJumpInterval } = useOptions()
return Jump {forwardJumpInterval}s
}
```
`getOptions` reports the *runtime* options above — it doesn't echo back the
setup-only `nowPlaying` / `playWhenReady` / `repeatMode` (read those via their
own getters/hooks, e.g. [`useRepeatMode`](/guide/queue#repeat-and-shuffle)).
## API summary
| API | Purpose |
| ------------------------------- | ------------------------------------------------------------------ |
| `setupPlayer(options?)` | Initialize (and reconfigure) the player; `async`, once at startup. |
| `updateOptions(options)` | Change runtime options later, merged over the current ones. |
| `getOptions()` / `useOptions()` | Read the current runtime options. |
| `onOptionsChanged` | Subscribe to options changes outside React. |
---
---
url: https://audiobrowser.dev/guide/track.md
description: >-
The Track shape — the single unit of content: required fields, identity,
metadata, and artwork, used for browse rows, queue items, and lock-screen
metadata.
---
# Track
A **Track** is the one unit of content in the library. The same object describes a row in a browse list, an item in the playback queue, and the metadata on the lock screen — so once you know the Track shape, you can read and build content everywhere.
A Track is just a plain object. The only required field is `title`, plus **at least one** of `path` (browsable) or `src` (playable):
```ts
const station: Track = {
title: 'Smooth Floret FM',
src: 'https://example.com/floret.mp3'
}
```
A real track usually carries more — identity, metadata, and artwork:
```ts
const episode: Track = {
id: 'atp-545',
title: 'Episode 545',
artist: 'Accidental Tech Podcast',
album: 'ATP',
artwork: 'https://example.com/atp.jpg',
duration: 7200,
src: 'https://example.com/atp/545.mp3'
}
```
This guide is the field-by-field reference. For *where* tracks come from (routes, callbacks, HTTP) see the [Browser](/guide/browser) guide.
## Browsable or playable
Two fields decide what a Track *does*. A Track must set at least one of them:
| Field | Makes the track | Effect |
| ------ | --------------- | ---------------------------------------------------- |
| `path` | **browsable** | a container — tapping it navigates into its children |
| `src` | **playable** | a leaf — the player can stream it |
```ts
// Browsable: a folder you navigate into
{ title: 'Jazz', path: '/browse/jazz' }
// Playable: a station you stream
{ title: 'Smooth Floret FM', src: 'https://example.com/floret.mp3' }
```
Set exactly one. On a browse page a track that sets both plays: the library replaces its `path` with one that points back to the page it appears on.
`src` is usually an absolute audio URL, but it can be any string — a file path or your own identifier — that you turn into a real request in `media.resolve` (see [Browser → Media and artwork](/guide/browser#media-and-artwork)).
## Identity: `id`
`id` is an **opaque, stable identifier** you control. The library never parses it — it round-trips verbatim through `setQueue`, the queue, `getActiveTrack`, and `onActiveTrackChanged`.
Why it matters: when playback moves by an *external* control — a lock-screen / CarPlay / Android Auto / Bluetooth next-or-previous — you find out which of *your* items became active by matching its `id`, without re-parsing the `src`:
```ts
// the callback gets a PlaybackActiveTrackChangedEvent — use event.track
const unsubscribe = onActiveTrackChanged.addListener((event) => {
const episode = myEpisodes.find((e) => e.id === event.track?.id)
// …update your UI for `episode`
})
```
The event also carries `index`, `lastTrack`, and `lastIndex`; `addListener` returns an unsubscribe function.
`id` is also passed to the per-track `resolve` hooks, so you can set `src` to the same stable identifier and synthesise the real request/artwork from it at request time.
::: tip `id` is optional
A track's identity is its `id`, falling back to `src` — so if the same item's `src` string is identical wherever it appears, you can skip `id` entirely.
Set ids consistently across your content or not at all: identity is compared whole, and a row carrying an `id` never matches a track without one. To compare tracks the same way in your own code, use [`getTrackIdentity`](/api/utils/getTrackIdentity/).
:::
## Display fields
These set the text shown across surfaces. Only `title` is required.
| Field | Shown where |
| ----------------------- | ---------------------------------------------------------------------------- |
| `title` | primary line — browse rows **and** now-playing (required) |
| `subtitle` | secondary line in **browse lists** only |
| `artist` | secondary line on **now-playing / lock screen**; the head-unit "artist" slot |
| `album` | album name (and gates the tappable album line — see `albumPath`) |
| `genre` / `description` | extra metadata |
| `duration` | catalog metadata in seconds, for your UI |
::: warning `subtitle` and `artist` are separate — neither falls back to the other
`subtitle` drives browse-list rows; `artist` drives the now-playing line and Bluetooth metadata. Set each one for the surface you want it on.
:::
`duration` is **catalog metadata only** (e.g. an episode list) — it does *not* drive the now-playing scrubber. Every surface derives elapsed/remaining from the player itself.
## Artwork
Set `artwork` to an image URL. It's transformed through your [artwork configuration](/guide/browser#media-and-artwork) and the ready-to-render result comes back on the **output-only** `artworkSource`, shaped for React Native's ``:
```tsx
```
Don't set `artworkSource` yourself — the library populates it.
**SF Symbols (iOS).** Prefix `artwork` with `sf:` to use a system symbol, with optional colors: `bg` (background) and `fg` (symbol). On the lock screen and in `artworkSource`, an omitted `bg` is transparent and an omitted `fg` is black:
```ts
{
title: 'Favorites',
path: '/favorites',
artwork: 'sf:heart.fill?bg=#FF0090&fg=#fff'
}
```
On CarPlay, an SF Symbol with no `fg` adapts to light/dark mode automatically: black on light grey or white on dark grey, and a `bg` alone is ignored.
**Tinting (`style: { artworkRendering: 'stencil' }`).** For monochrome icons, declare this so CarPlay tints them per appearance — black in light mode, white in dark. Use it for icons, not full-color album art. iOS CarPlay only; for Android Auto see [Tinting and platform icons](/guide/artwork#tinting-and-platform-icons).
On Android Auto, when a list or grid `display` applies and `artwork` is an `android.resource://` URI, the library asks for the category style, which adds margins around small icons.
**Light and dark images.** When the appearances need genuinely different artwork rather than the same shape recolored, set `artwork` to an [`ArtworkVariants`](/api/types/browser-nodes/#artworkvariants) pair — `{ light, dark }`. CarPlay adapts between them in place; everywhere that needs a single image uses `dark`. See [Artwork → Light and dark](/guide/artwork#light-and-dark-artwork).
## Per-track request override
[`request`](/api/types/browser-nodes/#trackrequest) is a **narrow** per-track field for *how* this track's audio request should be made.
[`TrackRequest`](/api/types/browser-nodes/#trackrequest) says which platforms merge it into the media request. Where they don't, return per-track headers or query from [`media.resolve`](/api/types/browser/#mediarequestconfig) (or `resolveSync`), which receives the track.
```ts
{
title: 'Member Stream',
src: 'https://example.com/members/floret.mp3',
request: { headers: { authorization: 'Bearer …' } }
}
```
It carries only `userAgent`, `headers`, and `query` — **not** `baseUrl` / `path` / `method` / `body`, so a track (often server-sourced) can't repoint its own host or verb. Like every field, it round-trips verbatim through the queue.
## Presentation on native surfaces
Optional fields that change how a Track renders on CarPlay / Android Auto. Each surface applies the ones it supports; an unsupported field is a no-op, never an error.
| Field | Effect | Platform |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| `style: { display: 'list' \| 'grid' }` | on a browsable track: the layout of the page it opens | Android Auto / AAOS |
| `style: { artworkRendering: 'stencil' }` | tint monochrome artwork to the surface appearance | CarPlay |
| `style: { imageShape: 'circular' }` | crop `'image'` and `'condensed'` tile artwork circular (people) | CarPlay (iOS 26+) |
| `style: { accessorySymbol: '…' }` | SF Symbol accessory; `'none'` restores the derived accessory | CarPlay |
| `style: { cardTint: '…', cardImage: '…' }` | card color and image mode, when the section renders `gridTile: 'card'` | CarPlay (iOS 26+) |
| `disabled` | unavailable: taps, voice selection, queue expansion and resume refuse it, but a `setQueue` list is not filtered and plays it when reached; grayed where drawable, hidden elsewhere | all |
| `favorited` | filled/empty heart (Android: needs the `favorite` capability; CarPlay: needs `'favorite'` in `ios.carPlayNowPlayingButtons`) | Android Auto, notification, CarPlay now-playing |
| `live` | a "live" indicator | iOS now-playing |
| `albumPath` | make the now-playing album line tappable | CarPlay |
Constraints worth knowing:
* **`display` goes on the browsable track as it appears in its parent's list** — Android Auto reads it there, before the page resolves, to decide how to lay out the page once you navigate in.
It is only sent when you declare it — the library never infers it from the page's content. The drilled-into page's own sections override it per section via their `style`.
* **`live` is more than an indicator.** On iOS it decides how a dropped or stalled stream recovers and stops a resume from seeking a stale position; on every platform, [`seekToLiveEdge()`](/api/features/playback/#seektoliveedge) does nothing unless the active track is declared live. Declare it on every live track — see [Live streams](/guide/live-streams).
* **`albumPath` requires `album`** (CarPlay renders the tappable line from album metadata), and pairs with `resolveAlbumPath` in the [Browser config](/guide/browser).
```ts
// This track as it appears in its parent's list (no children here — the
// page supplies those): it declares the layout of the page it opens.
{
path: '/genres',
title: 'Genres',
// the page this opens lays out as tiles in Android Auto
style: { display: 'grid' }
}
```
## Sections: grouping and tile layouts
A Track appears in two roles. As a **row** in its parent's list it's a handle: its own `style.display` only advertises the layout of the page it opens (see [above](#presentation-on-native-surfaces)). Once resolved, that same Track **is the page** — a [`ResolvedTrack`](/api/types/browser-nodes/#resolvedtrack) — and that is when it carries `sections`.
Headers and layout belong to the container role: declare them on the page's [`Section`](/api/types/browser-nodes/#section)s (`{ title?, style?, path?, children }`), never on the rows.
A section groups tracks under a header, and its `style` block's `display` picks their layout: `'list'` rows (the default) or `'grid'` artwork tiles — wrapping unless `gridWrap: false` keeps them to a single line.
The section's `path` is the navigation target for its header / "view all" surface; without one the header is a plain label, not a link — the section is self-contained.
A tile with `src` **plays immediately on tap** (same selection path as a playable list row — a station app can make tiles play their station directly); otherwise its `path` is navigated.
Tiles are ordinary Tracks, so playable ones carry the now-playing fields any track would (`id`, `artist`, `album`, `albumPath`, `live`, `request`). Tapping a playable child queues **its section** on every surface (see [Playback behavior](/guide/browser#playback-behavior)):
```ts
{
path: '/home',
title: 'Home',
sections: [
{
title: 'Featured',
style: { display: 'grid', gridWrap: false },
path: '/browse/featured', // header tap → the full list
children: [
{
title: 'Jazz',
path: '/browse/jazz',
artwork: 'https://…/jazz.jpg'
},
{
title: 'Beacon FM',
src: 'https://audio.example.com/beacon.mp3', // tap plays it
artist: 'Springfield',
live: true,
artwork: 'https://…/beacon.jpg'
}
]
},
{ title: 'All stations', children: [...] }
]
}
```
Each surface renders a declaration as its nearest supported form; see [Browser → Presentation](/guide/browser#presentation).
## ResolvedTrack: a resolved page
A [**`ResolvedTrack`**](/api/types/browser-nodes/#resolvedtrack) is the same Track plus its resolved content — the page the browser is currently showing. Its `path` is always present, and `sections` is the [`Section`](/api/types/browser-nodes/#section)`[]` to render (optional — a leaf page has none).
A page authored with a plain `children` list resolves to a single untitled section: `children` is authoring sugar, never populated on resolved output — read `sections`.
Navigation is **fire-and-forget**: `navigate(path)` returns `void`. Read the resolved page from `useContent()` (or `getContent()` / `onContentChanged`):
```tsx
import { navigate, useContent } from 'react-native-audio-browser'
navigate('/browse/jazz') // moves the browser to this path
function JazzPage() {
const page = useContent() // ResolvedTrack | undefined
// each section: { title?, style?, path?, children: Track[] }
return
// sections may be undefined
}
```
A `ResolvedTrack` may also set [`carPlaySiriListButton`](/api/types/browser/#carplaysirilistbuttonposition)`: 'top' | 'bottom'` to show the "Ask Siri to Play" cell on that page (needs Siri wiring — see [CarPlay](/guide/carplay)).
## Stream title encoding: `icyCharset`
Some Shoutcast / Icecast stations send their ICY stream titles in a legacy code page rather than UTF-8. Set `icyCharset` to its IANA label (`'windows-1251'`, …) and the player re-decodes those titles on iOS and Android. See [Metadata](/guide/metadata).
## Using tracks in your code
Tracks flow through the queue and playback API. A minimal playable track needs just `title` + `src`:
```ts
import { setQueue, play, useActiveTrack } from 'react-native-audio-browser'
setQueue([
{ title: 'Smooth Floret FM', src: 'https://example.com/floret.mp3' },
{ title: 'The Stalk 88.5', src: 'https://example.com/stalk.mp3' }
])
play()
```
`load(track)` replaces the active track (or starts the queue if it is empty), `add(tracks)` appends to the queue, and `getActiveTrack()` / `useActiveTrack()` read what's playing now (with its `artworkSource` populated for your UI). See [Basic Usage](/guide/basic-usage) for the full queue and playback API.
## Where to go next
* **[Browser](/guide/browser)** — where tracks come from: tabs, routes, sources.
* **[Now Playing](/guide/now-playing)** — how a track's fields drive the lock-screen / car metadata.
* **[Favorites](/guide/favorites)** — the `favorited` field and the heart button.
For the exact types — every field and its JSDoc — see [`Track`](/api/types/browser-nodes/#track) and [`ResolvedTrack`](/api/types/browser-nodes/#resolvedtrack) in the API reference.
---
---
url: https://audiobrowser.dev/guide/hooks.md
description: >-
The React hooks that keep your UI in sync with playback, the queue, the browse
tree, and the device — including changes driven from outside your app.
---
# Hooks
The library exposes its state as **React hooks** — call one in a component and it returns the current value and re-renders whenever that value changes.
They keep your in-app UI in sync with playback, the queue, the browse tree, and the device, including changes driven from *outside* your app (the lock screen, CarPlay, Android Auto, Bluetooth).
```tsx
import { useActiveTrack, usePlayingState } from 'react-native-audio-browser'
function NowPlaying() {
const track = useActiveTrack()
const { playing } = usePlayingState()
return (
{playing ? 'Playing' : 'Paused'}: {track?.title}
)
}
```
## The getter / hook / event trio
Most state comes in three forms, so you can read it whichever way fits:
| Form | Shape | Use it |
| ---------- | -------- | ------------------------------------------------------------ |
| **Hook** | `useX()` | inside a component — re-renders on change |
| **Getter** | `getX()` | a one-off synchronous read, anywhere |
| **Event** | `on…` | `onX.addListener(cb)` outside React — returns an unsubscribe |
Most events are named `onChanged`, but several aren't — `onProgressUpdated`, `onPlayingState`, `onPlaybackError`, `onNavigationError`. The exact event for each hook is in the [reference table](#all-hooks-at-a-glance), so don't guess the name.
```ts
import { getPlayback, onPlaybackChanged } from 'react-native-audio-browser'
const now = getPlayback() // read once
// subscribe
const stop = onPlaybackChanged.addListener((p) => console.log(p.state))
// stop() to unsubscribe
```
Every hook, getter, and event is a named export from `react-native-audio-browser`. Hooks read a cached value synchronously on first render (no flash of empty state) and then subscribe for you, except `usePolledProgress`, which starts at zero and fills in on its first poll.
Mutating state is separate — `setX()` / action functions (`play`, `setQueue`, `setShuffle`, `setRepeatMode`, `setPlayWhenReady`, …) — covered in [Basic Usage](/guide/basic-usage).
## Playback
The transport state — what the player is doing right now.
```tsx
import {
usePlayback,
usePlayingState,
useProgress
} from 'react-native-audio-browser'
function Transport() {
const { state } = usePlayback() // e.g. 'playing' | 'paused' (full list below)
const { playing, buffering } = usePlayingState()
const { position, duration, buffered } = useProgress() // seconds
return
}
```
* [**`usePlayback()`**](/api/features/playback/#useplayback) → `{ state, error? }`. `state` is one of `none`, `ready`, `loading`, `buffering`, `playing`, `paused`, `stopped`, `ended`, `error`.
* [**`usePlayingState()`**](/api/features/playback/#useplayingstate) → `{ playing, buffering }`. A lighter hook when you only need the booleans.
* [**`useProgress()`**](/api/features/playback/#useprogress) → [`Progress`](/api/features/playback/#progress) (`{ position, duration, buffered }`) in seconds. Event-driven, but **off by default**: `progressUpdateEventInterval` is `null` until you set it (in seconds) in `setupPlayer` or `updateOptions`, e.g. `progressUpdateEventInterval: 0.5` — otherwise the value never ticks.
* [**`usePolledProgress(updateInterval = 1000)`**](/api/features/playback/#usepolledprogress) → same [`Progress`](/api/features/playback/#progress), but polled on its own timer (milliseconds) instead of event-driven, so it works without `progressUpdateEventInterval`. Good for a smooth scrubber; it pauses while the app is backgrounded.
* [**`usePlayWhenReady()`**](/api/features/playback/#useplaywhenready) → `boolean`: whether the player will start as soon as content is ready.
* [**`useSystemVolume()`**](/api/features/playback/#usesystemvolume) → `number` 0–1, the device volume (read-only on iOS).
::: tip `useProgress` vs `usePolledProgress`
`useProgress` emits at the global `progressUpdateEventInterval` (and stays still until you set it); `usePolledProgress` ignores that and ticks on its own timer. For a scrubber, `usePolledProgress` is usually the simpler choice.
:::
## Queue and active track
```tsx
import {
getTrackIdentity,
useActiveTrack,
useQueue,
useRepeatMode,
useShuffle
} from 'react-native-audio-browser'
function QueueScreen() {
const active = useActiveTrack() // Track | undefined
const queue = useQueue() // Track[]
const repeat = useRepeatMode() // 'off' | 'track' | 'queue'
const shuffle = useShuffle() // boolean
return
}
```
[`useActiveTrack`](/api/features/queue/#useactivetrack) updates even when the track changes from an external control (car next/previous), so matching on the track's identity keeps your UI correct. Compare tracks by identity: `id` when set, else `src`. [`getTrackIdentity(track)`](/api/utils/getTrackIdentity/) gives you the same comparison the library uses (see [Track](/guide/track#identity-id)).
## Now playing
[**`useNowPlaying()`**](/api/features/nowPlaying/#usenowplaying) → [`NowPlayingMetadata`](/api/features/metadata/#nowplayingmetadata)` | undefined` — the metadata shown on the lock screen and car surfaces.
On iOS and Android it returns what those surfaces show, in priority order: a `flashNowPlaying()` flash first, then your `nowPlaying` formatter, then any override you set via `updateNowPlaying()` (e.g. the current song on a live stream), then the active track's own fields. On web there is no formatter, and a flash replaces your override (see [the flash](/guide/now-playing#the-flash-transient-top-priority)). See [the four metadata layers](/guide/now-playing#the-four-metadata-layers).
```tsx
const meta = useNowPlaying()
// { title?, artist?, album?, artwork?, genre?, duration?,
// description?, mediaId?, elapsedTime? (iOS only, not live) }
```
[**`useTimedMetadata()`**](/api/features/metadata/#usetimedmetadata) → [`TimedMetadata`](/api/features/metadata/#timedmetadata)` | undefined` — the stream's current song (ICY or ID3), cleared on a track change until the next one arrives. Always `undefined` on web.
## Browsing
Mirror the browse tree your app draws — the same state CarPlay and Android Auto render.
* [**`useTabs()`**](/api/features/browser/#usetabs) → [`Track`](/api/types/browser-nodes/#track)`[] | undefined` — the top-level tabs.
* [**`usePath()`**](/api/features/browser/#usepath) → `string | undefined` — the current browse path.
* [**`useContent()`**](/api/features/browser/#usecontent) → [`ResolvedTrack`](/api/types/browser-nodes/#resolvedtrack)` | undefined` — the resolved page (`content?.sections` to render — each a titled, styled group of tracks).
```tsx
import { useContent, navigate } from 'react-native-audio-browser'
function Browse() {
const page = useContent()
// each section: { title?, style?, path?, children: Track[] }
return (
navigate(track)}
/>
)
}
```
See [Browser](/guide/browser) for how navigation and content resolution work.
## Sleep timer
* [**`useSleepTimerActive()`**](/api/features/sleepTimer/#usesleeptimeractive) → `boolean` — lightweight "is a timer set?" check.
* [**`useSleepTimer(params?)`**](/api/features/sleepTimer/#usesleeptimer) → the live [`SleepTimerState`](/api/features/sleepTimer/#sleeptimerstate), or `undefined` when none is set:
* `{ time, secondsLeft }` for a countdown timer (`time` is the epoch-ms fire time), or
* `{ sleepWhenPlayedToEnd: true }` for an end-of-track timer.
```tsx
const timer = useSleepTimer({ updateInterval: 1000 })
// timer && 'secondsLeft' in timer → show timer.secondsLeft
```
`params` takes `updateInterval` (countdown tick rate, default 1000ms) and `inactive` (set `true` while backgrounded to pause ticking). `secondsLeft` does not advance in the background.
## Device and environment
| Hook | Returns | Notes |
| ------------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------- |
| [`useOnline()`](/api/features/network/#useonline) | `boolean` | network connectivity |
| [`useCarConnected()`](/api/features/carConnection/#usecarconnected) | `boolean` | CarPlay / Android Auto connected (`false` on web) |
| [`useSystemVolume()`](/api/features/playback/#usesystemvolume) | `number` | device volume 0–1 |
| [`useOutput()`](/api/features/output/#useoutput) | [`Output`](/api/features/output/#output)` \| undefined` | current audio output (iOS + Android) |
```tsx
const output = useOutput() // { type, name, external } | undefined
// e.g. output?.type === 'bluetooth', output?.external === true
```
`useOutput` updates as routes change (AirPods connect, a Bluetooth speaker is selected, etc.); it's `undefined` when unknown. On Android below 13 (API 33) it can miss a reroute made while a device stays connected; see [The current output](/guide/audio-output#the-current-output).
## Errors
* [**`usePlaybackError()`**](/api/features/errors/#useplaybackerror) → [`PlaybackError`](/api/features/errors/#playbackerror)` | undefined` — playback failures, with a normalized `kind` (`offline`, `unreachable`, `not-found`, `rejected`, `unplayable`, `stalled`, …) to branch on, plus a platform-specific `code` and optional `statusCode` for telemetry. Never show its `message` — see [Errors](/guide/errors#playback-errors). Terminal errors only: an error the player is still retrying (`retrying: true`) arrives on `usePlayback().error` — see [Errors while retrying](/guide/errors#errors-while-retrying).
* [**`useNavigationError()`**](/api/features/errors/#usenavigationerror) → [`NavigationError`](/api/features/errors/#navigationerror)` | undefined` — a browse/search failure, with a typed `code` (`network-error`, `http-error`, `timeout`, `empty-content`, …) and optional `statusCode`.
* [**`useFormattedNavigationError()`**](/api/features/errors/#useformattednavigationerror) → [`FormattedNavigationError`](/api/features/errors/#formattednavigationerror)` | undefined` (`{ title, message? }`) — the same error run through your `formatNavigationError` config (the copy CarPlay and Android Auto show), ready to display.
```tsx
const error = useFormattedNavigationError()
return error ? : null
```
## Player options
[**`useOptions()`**](/api/features/player/#useoptions) → the current [`Options`](/api/features/player/#options) (jump intervals, `capabilities`, and the `android` / `ios` blocks). Mutate with `updateOptions(partial)`.
```tsx
const { forwardJumpInterval, capabilities } = useOptions()
```
## Android-only hooks
**Battery** (Android background-restriction state — all `false`/`unrestricted` on iOS):
* [**`useBatteryWarning()`**](/api/features/battery/#usebatterywarning) → `{ pending, status, dismiss, openSettings }` — the meta-hook for a complete warning UI; `dismiss()` and `openSettings()` are ready-to-wire actions.
* [**`useBatteryWarningPending()`**](/api/features/battery/#usebatterywarningpending) → `boolean` and [**`useBatteryOptimizationStatus()`**](/api/features/battery/#usebatteryoptimizationstatus) → `'unrestricted' | 'optimized' | 'restricted'` are the individual pieces.
```tsx
const { pending, status, dismiss, openSettings } = useBatteryWarning()
```
**Equalizer**: [**`useEqualizerSettings()`**](/api/features/equalizer/#useequalizersettings) → [`EqualizerSettings`](/api/features/equalizer/#equalizersettings)` | undefined` (`bandLevels`, `presets`, `enabled`, …); `undefined` on iOS. Drive it with `setEqualizerEnabled` / `setEqualizerPreset` / `setEqualizerLevels`.
## Debugging
[**`useDebug(options?)`**](/api/utils/useDebug/#usedebug) → `{ state, logs, clear }` — a live snapshot of the core player state (playback, queue, options, browse path, errors) plus a bounded log of recent changes. It's a development aid; `options.enabled` defaults to `__DEV__`.
```tsx
const { state, logs, clear } = useDebug({ metadata: true })
```
## All hooks at a glance
The **Event** column is the emitter for the getter/event form, the **Hook** name links to its full API entry, and the **Returns** type links to its definition where it has one.
| Hook | Returns | Event | Platform |
| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------ | ------------------- |
| [`usePlayback`](/api/features/playback/#useplayback) | `{ state, error? }` | `onPlaybackChanged` | all |
| [`usePlayingState`](/api/features/playback/#useplayingstate) | `{ playing, buffering }` | `onPlayingState` | all |
| [`useProgress`](/api/features/playback/#useprogress) | `{ position, duration, buffered }` | `onProgressUpdated` | all |
| [`usePolledProgress`](/api/features/playback/#usepolledprogress) | `{ position, duration, buffered }` | *(polled)* | all |
| [`usePlayWhenReady`](/api/features/playback/#useplaywhenready) | `boolean` | `onPlayWhenReadyChanged` | all |
| [`useSystemVolume`](/api/features/playback/#usesystemvolume) | `number` | `onSystemVolumeChanged` | all (read-only iOS) |
| [`useActiveTrack`](/api/features/queue/#useactivetrack) | [`Track`](/api/types/browser-nodes/#track)` \| undefined` | `onActiveTrackChanged` | all |
| [`useQueue`](/api/features/queue/#usequeue) | [`Track`](/api/types/browser-nodes/#track)`[]` | `onQueueChanged` | all |
| [`useRepeatMode`](/api/features/queue/#userepeatmode) | [`RepeatMode`](/api/features/queue/#repeatmode) | `onRepeatModeChanged` | all |
| [`useShuffle`](/api/features/queue/#useshuffle) | `boolean` | `onShuffleChanged` | all |
| [`useNowPlaying`](/api/features/nowPlaying/#usenowplaying) | `NowPlayingMetadata \| undefined` | `onNowPlayingChanged` | all |
| [`useTimedMetadata`](/api/features/metadata/#usetimedmetadata) | [`TimedMetadata`](/api/features/metadata/#timedmetadata)` \| undefined` | `onTimedMetadata` | iOS, Android |
| [`useTabs`](/api/features/browser/#usetabs) | [`Track`](/api/types/browser-nodes/#track)`[] \| undefined` | `onTabsChanged` | all |
| [`usePath`](/api/features/browser/#usepath) | `string \| undefined` | `onPathChanged` | all |
| [`useContent`](/api/features/browser/#usecontent) | [`ResolvedTrack`](/api/types/browser-nodes/#resolvedtrack)` \| undefined` | `onContentChanged` | all |
| [`useSleepTimerActive`](/api/features/sleepTimer/#usesleeptimeractive) | `boolean` | `onSleepTimerChanged` | all |
| [`useSleepTimer`](/api/features/sleepTimer/#usesleeptimer) | [`SleepTimerState`](/api/features/sleepTimer/#sleeptimerstate)` \| undefined` | `onSleepTimerChanged` | all |
| [`useOnline`](/api/features/network/#useonline) | `boolean` | `onOnlineChanged` | all |
| [`useCarConnected`](/api/features/carConnection/#usecarconnected) | `boolean` | `onCarConnectedChanged` | all (`false` web) |
| [`useOutput`](/api/features/output/#useoutput) | [`Output`](/api/features/output/#output)` \| undefined` | `onOutputChanged` | iOS, Android |
| [`usePlaybackError`](/api/features/errors/#useplaybackerror) | [`PlaybackError`](/api/features/errors/#playbackerror)` \| undefined` | `onPlaybackError` | all |
| [`useNavigationError`](/api/features/errors/#usenavigationerror) | [`NavigationError`](/api/features/errors/#navigationerror)` \| undefined` | `onNavigationError` | all |
| [`useFormattedNavigationError`](/api/features/errors/#useformattednavigationerror) | [`FormattedNavigationError`](/api/features/errors/#formattednavigationerror)` \| undefined` | `onFormattedNavigationError` | all |
| [`useOptions`](/api/features/player/#useoptions) | [`Options`](/api/features/player/#options) | `onOptionsChanged` | all |
| [`useBatteryWarning`](/api/features/battery/#usebatterywarning) | `{ pending, status, dismiss, openSettings }` | *(composite)* | Android |
| [`useBatteryWarningPending`](/api/features/battery/#usebatterywarningpending) | `boolean` | `onBatteryWarningPendingChanged` | Android |
| [`useBatteryOptimizationStatus`](/api/features/battery/#usebatteryoptimizationstatus) | [`BatteryOptimizationStatus`](/api/features/battery/#batteryoptimizationstatus) | `onBatteryOptimizationStatusChanged` | Android |
| [`useEqualizerSettings`](/api/features/equalizer/#useequalizersettings) | [`EqualizerSettings`](/api/features/equalizer/#equalizersettings)` \| undefined` | `onEqualizerChanged` | Android |
| [`useDebug`](/api/utils/useDebug/#usedebug) | `{ state, logs, clear }` | *(composite)* | all |
For the exact return types, see the [API reference](/api/).
---
---
url: https://audiobrowser.dev/guide/migrating-from-track-player.md
description: >-
Porting from react-native-track-player v4: what carries over unchanged, what
was renamed or reshaped, and what is new.
---
# Migrating from react-native-track-player
Most playback and queue calls from
[react-native-track-player](https://github.com/doublesymmetry/react-native-track-player/tree/v4)
(RNTP) v4 keep their names and meaning in `react-native-audio-browser`. This
page lists what changes.
RNTP v5 moved to a
[commercial license](https://github.com/doublesymmetry/react-native-track-player).
`react-native-audio-browser` is MIT.
## What ports over unchanged
These are the same calls with the same meaning. `import` them from
`react-native-audio-browser` instead of `react-native-track-player`:
[`add`](/api/features/queue/#add), [`remove`](/api/features/queue/#remove), [`move`](/api/features/queue/#move),
[`skip`](/api/features/queue/#skip), [`skipToNext`](/api/features/queue/#skiptonext),
[`skipToPrevious`](/api/features/queue/#skiptoprevious), [`setQueue`](/api/features/queue/#setqueue),
[`getQueue`](/api/features/queue/#getqueue), [`getTrack`](/api/features/queue/#gettrack),
[`removeUpcomingTracks`](/api/features/queue/#removeupcomingtracks), [`load`](/api/features/queue/#load),
[`reset`](/api/features/playback/#reset), [`retry`](/api/features/playback/#retry),
[`play`](/api/features/playback/#play), [`pause`](/api/features/playback/#pause),
[`stop`](/api/features/playback/#stop), [`seekTo`](/api/features/playback/#seekto),
[`seekBy`](/api/features/playback/#seekby), [`setRate`](/api/features/playback/#setrate),
[`getRate`](/api/features/playback/#getrate), [`setVolume`](/api/features/playback/#setvolume),
[`getVolume`](/api/features/playback/#getvolume), [`setRepeatMode`](/api/features/queue/#setrepeatmode),
[`getRepeatMode`](/api/features/queue/#getrepeatmode), [`setPlayWhenReady`](/api/features/playback/#setplaywhenready),
[`getPlayWhenReady`](/api/features/playback/#getplaywhenready), [`getActiveTrack`](/api/features/queue/#getactivetrack),
[`getActiveTrackIndex`](/api/features/queue/#getactivetrackindex).
[`setupPlayer`](/api/features/player/#setupplayer) and
[`updateOptions`](/api/features/player/#updateoptions) keep their names, but
their options changed shape. See [Player options](#player-options).
The differences below are what to watch for.
## Getters are synchronous — and there are hooks
RNTP getters return Promises; audio-browser getters return the value
**synchronously**, and most have a reactive **hook**. Drop the `await` (awaiting a
non-Promise returns the value, so this isn't urgent), and prefer the hook in React.
| RNTP v4 | audio-browser |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `await getPosition()` | [`getProgress().position`](/api/features/playback/#position) |
| `await getDuration()` | [`getProgress().duration`](/api/features/playback/#duration) |
| `await getBufferedPosition()` | [`getProgress().buffered`](/api/features/playback/#buffered) |
| `await getProgress()` | [`getProgress()`](/api/features/playback/#getprogress) (sync) / [`usePolledProgress()`](/api/features/playback/#usepolledprogress) |
| `await getState()` | [`getPlayback().state`](/api/features/playback/#state) |
| `await getPlaybackState()` | [`getPlayback()`](/api/features/playback/#getplayback) / [`usePlayback()`](/api/features/playback/#useplayback) |
| `await getActiveTrack()` | [`getActiveTrack()`](/api/features/queue/#getactivetrack) / [`useActiveTrack()`](/api/features/queue/#useactivetrack) |
| `await getQueue()` | [`getQueue()`](/api/features/queue/#getqueue) / [`useQueue()`](/api/features/queue/#usequeue) |
| `await getRepeatMode()` | [`getRepeatMode()`](/api/features/queue/#getrepeatmode) / [`useRepeatMode()`](/api/features/queue/#userepeatmode) |
Two hook gotchas:
* **`useProgress` changed meaning.** RNTP's `useProgress(interval)` is polling;
its drop-in is [`usePolledProgress(intervalMs)`](/api/features/playback/#usepolledprogress).
audio-browser *also* has a [`useProgress()`](/api/features/playback/#useprogress), but it's **event-based and takes no
interval**. It stays still until `progressUpdateEventInterval` is set.
TypeScript rejects `useProgress(2000)`; plain JS ignores the argument.
* **`useIsPlaying()` → [`usePlayingState()`](/api/features/playback/#useplayingstate)**,
but the field is renamed: RNTP's `{ playing, bufferingDuringPlay }` becomes
`{ playing, buffering }`.
## Events: per-event `on*` / `use*`, no `Event` enum
RNTP centralizes events behind the `Event` enum with `addEventListener` /
`useTrackPlayerEvents`. audio-browser exposes one emitter (and usually a hook)
per event, and `addListener` returns an **unsubscribe function** (not a
subscription with `.remove()`):
```ts
// RNTP
import TrackPlayer, { Event } from 'react-native-track-player'
const sub = TrackPlayer.addEventListener(
Event.PlaybackActiveTrackChanged,
(e) => {}
)
sub.remove()
// audio-browser
import { onActiveTrackChanged } from 'react-native-audio-browser'
const unsubscribe = onActiveTrackChanged.addListener((e) => {})
unsubscribe()
```
| RNTP `Event.*` | audio-browser |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PlaybackActiveTrackChanged` | [`onActiveTrackChanged`](/api/features/queue/#onactivetrackchanged) / [`useActiveTrack()`](/api/features/queue/#useactivetrack) |
| `PlaybackState` | [`onPlaybackChanged`](/api/features/playback/#onplaybackchanged) / [`usePlayback()`](/api/features/playback/#useplayback) |
| `PlaybackProgressUpdated` | [`onProgressUpdated`](/api/features/playback/#onprogressupdated) / [`useProgress()`](/api/features/playback/#useprogress) |
| `PlaybackQueueEnded` | [`onQueueEnded`](/api/features/queue/#onqueueended) |
| `PlaybackError` / `PlayerError` | [`onPlaybackError`](/api/features/errors/#onplaybackerror) / [`usePlaybackError()`](/api/features/errors/#useplaybackerror) |
| `PlaybackPlayWhenReadyChanged` | [`onPlayWhenReadyChanged`](/api/features/playback/#onplaywhenreadychanged) / [`usePlayWhenReady()`](/api/features/playback/#useplaywhenready) |
| `Remote*` (Play, Pause, Next, …) | `handleRemote*` to override, `onRemote*` to observe — see [Remote Controls](/guide/remote-controls) |
| `Metadata*Received` | [`onTimedMetadata`](/api/features/metadata/#ontimedmetadata) / [`onChapterMetadata`](/api/features/metadata/#onchaptermetadata) / [`onTrackMetadata`](/api/features/metadata/#ontrackmetadata) — see [Metadata](/guide/metadata) |
## Delete the playback service
RNTP requires `registerPlaybackService(() => require('./service'))` and a service
file that wires `Event.RemotePlay → TrackPlayer.play()`, etc. **audio-browser has
no playback service** — the library wires the native side itself, and remote
controls drive the player by default. Delete the service file and the
registration call.
To customize a remote control, set a
[`handleRemote*`](/guide/remote-controls) override (pass `undefined` to restore
the default); to just observe, use `onRemote*`:
```ts
import { handleRemoteNext, skipToNext } from 'react-native-audio-browser'
// Override "next" (call the default action yourself if you still want it):
handleRemoteNext(() => skipToNext())
handleRemoteNext(undefined) // restore the default
```
Audio interruptions (RNTP's `Event.RemoteDuck`) are handled natively, so the
duck handler in your service can go too. On Android,
`android.audioContentType: 'speech'` pauses on an interruption instead of
ducking.
## `capabilities`: an object, not an array
```ts
// RNTP
import { Capability } from 'react-native-track-player'
await TrackPlayer.updateOptions({
capabilities: [Capability.Play, Capability.Pause, Capability.SkipToNext]
})
// audio-browser — most are ON by default; specify only what differs
updateOptions({ capabilities: { skipToPrevious: false } })
```
Pass `capabilities` to **either** [`setupPlayer`](/api/features/player/#setupplayer)
(initial) or [`updateOptions`](/api/features/player/#updateoptions) (later) — both
accept it. See
[Configuration → Capabilities](/guide/configuration#capabilities) for the
defaults.
`Capability.Like` / `RatingType` map to the [`favorite`](/guide/favorites)
capability.
## Enums become string literals
audio-browser has no enum objects — use the string values directly:
| RNTP | audio-browser |
| ------------------------------------ | --------------------------------------------- |
| `State.Playing`, `State.Paused`, … | `'playing'`, `'paused'`, … (same strings) |
| `RepeatMode.Off` / `Track` / `Queue` | `'off'` / `'track'` / `'queue'` |
| `Capability.Play` (in an array) | `{ play: true }` (in the capabilities object) |
`State`'s string values are identical, so `state === 'playing'` checks port
directly — you just drop the enum import.
## `Track`: `url` → `src`
The playable URL field is renamed. In audio-browser, the **playable source**
is [`src`](/api/types/browser-nodes/#src); a track's **browse address** (for the
[browse tree](/guide/browser)) is a separate field, `path`:
```ts
// RNTP
{ url: 'https://cdn.example.com/song.mp3', title, artist, artwork }
// audio-browser
{ src: 'https://cdn.example.com/song.mp3', title, artist, artwork }
```
Other field changes:
* `isLiveStream` → [`live`](/api/types/browser-nodes/#live).
* Per-track `headers` / `userAgent` → return them from `media.resolve(track)`
(or `resolveSync`), which receives each track. Headers that every track
shares go on the browser's `request` / `media` config
([Shaping requests](/guide/browser#shaping-requests)).
* `rating` → favorites (see above).
* `title` is required.
* `Track` has no index signature, so it refuses fields of your own. Keep app
data in a map keyed by `id` (or by `src`).
* RNTP's `type`, `contentType`, `pitchAlgorithm` and `date` have no `Track`
field.
`title` / `artist` / `album` / `artwork` / `duration` / `description` /
`genre` are unchanged.
## Now-playing metadata
```ts
// RNTP
TrackPlayer.updateNowPlayingMetadata({ title, artist })
TrackPlayer.clearNowPlayingMetadata()
// audio-browser
import { updateNowPlaying } from 'react-native-audio-browser'
updateNowPlaying({ title, artist })
updateNowPlaying(null) // drop the override; the track's own metadata shows
```
For live streams, prefer the [Now Playing formatter](/guide/now-playing) over
imperative updates — it re-derives the lock-screen lines on every metadata /
state change.
## Player options
`setupPlayer` and `updateOptions` keep `capabilities`,
`forwardJumpInterval`, `backwardJumpInterval` and
`progressUpdateEventInterval`. Other RNTP options moved or have no
equivalent:
| RNTP v4 | audio-browser |
| -------------------------------------------------------- | --------------------------------------------------------------- |
| `minBuffer` / `maxBuffer` / `backBuffer` / `playBuffer` | `android.minBuffer` / `maxBuffer` / `backBuffer` / `playBuffer` |
| `minBuffer` on iOS | `ios.buffer` |
| `maxCacheSize` | `android.maxCacheSize` |
| `androidAudioContentType` | `android.audioContentType` |
| `iosCategory` / `iosCategoryMode` / `iosCategoryOptions` | `ios.category` / `ios.categoryMode` / `ios.categoryOptions` |
| `autoUpdateMetadata` | `nowPlaying` |
| `notificationCapabilities` / `compactCapabilities` | none; place Android buttons with `android.remoteButtonLayout` |
| `icon` / `color` | none |
| `ratingType` | the `favorite` capability |
The units changed with the names. The four Android buffers and `ios.buffer`
take milliseconds where RNTP took seconds, and `maxCacheSize` takes megabytes
where RNTP took kilobytes, so a value copied across unchanged is off by a
factor of 1000.
The `android` and `ios` keys are typed, so a leftover RNTP option is a type
error. See [Configuration](/guide/configuration) for every option.
## Setup, before and after
```ts
// RNTP — index.js + startup
TrackPlayer.registerPlaybackService(() => require('./service'))
await TrackPlayer.setupPlayer()
await TrackPlayer.updateOptions({
capabilities: [Capability.Play, Capability.Pause, Capability.SkipToNext],
progressUpdateEventInterval: 2
})
```
```ts
// audio-browser — one declarative call, no service
import { setupPlayer } from 'react-native-audio-browser'
await setupPlayer({
progressUpdateEventInterval: 2
// capabilities are on by default; nothing to register
})
```
See [Configuration](/guide/configuration) for the full options surface and what's
setup-only vs runtime-updatable.
## What you gain
audio-browser adds capabilities RNTP doesn't have — worth adopting once you've
ported:
* A [**browse tree**](/guide/browser) that powers native **CarPlay** and
**Android Auto** menus (and voice [search](/guide/search)) — see the
[Automotive overview](/guide/automotive).
* A [**now-playing formatter**](/guide/now-playing) for live-stream metadata and
transient status lines.
* [**Content gating**](/guide/gate), a [**sleep timer**](/guide/sleep-timer),
an [**equalizer**](/guide/equalizer), and [**favorites**](/guide/favorites).
## Quick reference
| Area | RNTP v4 | audio-browser |
| --------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| Getters | `await TrackPlayer.getX()` | `getX()` (sync) or `useX()` |
| Events | `Event` + `addEventListener` / `useTrackPlayerEvents` | per-event `onX` / `useX` |
| Unsubscribe | `subscription.remove()` | the function `addListener` returns |
| Remote handling | a registered playback **service** | default behavior + `handleRemote*` |
| Capabilities | `Capability[]` | `capabilities` object of booleans |
| Enums | `State.*`, `RepeatMode.*` | string literals (`'playing'`, `'queue'`) |
| Playable URL | `track.url` | [`track.src`](/api/types/browser-nodes/#src) |
| Live flag | `track.isLiveStream` | [`track.live`](/api/types/browser-nodes/#live) |
| Now playing | `updateNowPlayingMetadata` / `clearNowPlayingMetadata` | [`updateNowPlaying`](/api/features/nowPlaying/#updatenowplaying)`(update \| null)`; `null` reverts to the track's metadata |
---
---
url: https://audiobrowser.dev/guide/artwork.md
description: >-
Set Track.artwork once and render it everywhere: the fetch and transform
pipeline, per-surface sizing, SF Symbols, tinting, light/dark pairs, Android
vector icons, and SVG.
---
# Artwork
**Artwork** is the image shown for a track — the thumbnail in a browse list, the cover on the lock screen, the icon on a CarPlay row.
You set one field, `artwork`, on a [`Track`](/guide/track); the library resolves and transforms it per surface and per requested size, and hands the ready-to-render result back on `artworkSource`.
This guide covers the mental model (the two configs and the output field), **which artwork renders where**, and the **transform pipeline** that turns your URL into a sized request. It then covers the platform-specific bits: SF Symbols on iOS, tinting, light/dark artwork, Android vector icons, and SVG.
## Mental model
Three names do all the work:
| Name | What it is | You |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------- |
| `Track.artwork` | The image **you set** — an `https` URL, an `sf:` symbol (iOS), a platform URI, or a `{ light, dark }` pair. | set it |
| `artwork` / `nowPlayingArtwork` config | How the library **fetches** that image (base URL, headers, signing, sizing). | configure once (override per route / for now-playing) |
| `Track.artworkSource` | The resolved, ready-to-render [`ImageSource`](/api/types/browser-nodes/#imagesource) (URL + headers) the library **produces**. | read it |
`artwork` is the only field you set per track. `artworkSource` is **output-only** — the library populates it; never set it yourself.
```tsx
import { useActiveTrack } from 'react-native-audio-browser'
import { Image } from 'react-native'
function Cover() {
const track = useActiveTrack()
// artworkSource is the transformed result, shaped for
return
}
```
## Which artwork renders where
The library publishes art to several surfaces; each gets its image from a field/config and (where the surface knows its display size) a size hint:
| Surface | Image from | Size hint | Tinting |
| --------------------------------------------- | --------------------------------------------- | --------- | ------------------------------------------------------------------------------ |
| **CarPlay browse rows / tabs** | `artwork` (global config; no per-route) | yes | `style: { artworkRendering: 'stencil' }`, or a `{ light, dark }` pair |
| **Android Auto browse rows** | `artwork` (per-route override allowed) | no | — (see [Tinting](#tinting-and-platform-icons)) |
| **In-app ``** | `artworkSource` (output) | no | your UI |
| **iOS lock screen / Control Center** | `nowPlayingArtwork` → falls back to `artwork` | yes | — |
| **CarPlay Now Playing** | `nowPlayingArtwork` → `artwork` | yes | — |
| **Android notification / Android Auto** | `nowPlayingArtwork` → `artwork` | yes | — (see [Tinting](#tinting-and-platform-icons)) |
| **CarPlay tile sections** (`display: 'grid'`) | `artwork` (each tile is a Track) | yes | CarPlay: `style: { artworkRendering: 'stencil' }`, or a `{ light, dark }` pair |
**Size hint** = the surface tells the library the pixels it needs, delivered as an [`ImageContext`](/api/types/browser/#imagecontext) to your `transform` / `imageQueryParams`. Browse-time resolution, which produces `artworkSource` and the Android Auto browse URLs, has none.
Three things to take from the table:
* **One image by default.** With only `artwork` set, the same source feeds browse rows *and* every now-playing surface. Set `nowPlayingArtwork` only when the now-playing image should differ (a larger, lock-screen-quality cover without bloating list thumbnails).
* **Size hints exist only where the surface knows its size.** Browse-time resolution (`artworkSource`, Android Auto browse rows) has no size, so `imageQueryParams` and `context` (below) do nothing there; they kick in when CarPlay loads a row, tab or tile, and on now-playing surfaces.
* **Tinting is for browse icons only.** `artworkRendering: 'stencil'` is applied when CarPlay renders browse content — list rows, tabs, and tiles — not to now-playing cover art.
## The transform pipeline
`artwork` is an [`ArtworkRequestConfig`](/api/types/browser/#artworkrequestconfig). When the library needs a track's image, it builds the request in layers, each overriding the last:
1. **`request`** — shared base config (user agent, common headers).
2. **`artwork`** — the static image config (`baseUrl`, `headers`, …).
3. **`resolve(track)` / `resolveSync(track)`** — per-track overrides built from the track's metadata.
4. **`imageQueryParams`** — appends the surface's requested size (when it reports one).
5. **`transform({ request, context })` / `transformSync`** — final tweak, with the requested size in `context`.
To build a per-track URL, use `resolve` (the track is the argument). On iOS and Android, an `{id}` token in an artwork config's `path`, `query` or `headers` is replaced with the track's `id`. This applies to `artwork`, a route's `artwork` and `nowPlayingArtwork` alike. The web implementation sends static values verbatim.
A typical CDN setup never needs more than `baseUrl` plus `imageQueryParams`:
```ts
import { configureBrowser } from 'react-native-audio-browser'
configureBrowser({
// ...the rest of your config (tabs, routes, …)
artwork: {
baseUrl: 'https://images.example.com',
// tell the library which query params carry the requested size
imageQueryParams: { width: 'w', height: 'h' }
}
})
```
With [`imageQueryParams`](/api/types/browser/#imagequeryparams) the requested size from CarPlay / Android Auto is appended automatically — `?w=200&h=200` — so each surface gets right-sized art. Omit `height` to send width only. This only fires on surfaces that report a size; `artworkSource` and Android Auto browse rows (no size hint) get the URL without these params.
For anything `imageQueryParams` can't express — per-track paths, signed URLs — use `resolve` and `transform` (or their sync variants):
```ts
import { configureBrowser } from 'react-native-audio-browser'
// add: yarn add crypto-js
import HmacSHA256 from 'crypto-js/hmac-sha256'
// your CDN signing key
const CDN_KEY = process.env.CDN_KEY ?? ''
// sign the path locally with your key — a pure, sync function
const signUrl = (path: string) => HmacSHA256(path, CDN_KEY).toString()
configureBrowser({
artwork: {
baseUrl: 'https://images.example.com',
// build the path from the track (sync — no await needed)
resolveSync: (track) => ({ path: `/covers/${track.id}.jpg` }),
// then sign it + size it. both are sync, so no Promise is
// allocated per image
transformSync: ({ request, context }) => ({
...request,
query: {
...request.query,
w: context?.width ? String(context.width) : '600',
// path is optional in the type; resolveSync above always sets it
sig: signUrl(request.path ?? '')
}
})
}
})
```
A `transform` (or `transformSync`) **replaces** the request — it doesn't merge — so spread `...request` (and `...request.query`) or you'll drop the `baseUrl` and other layers. The [`context`](/api/types/browser/#imagecontext) is an `ImageContext` with `width` / `height` in **pixels**, present only when the surface knows its display size (so guard with `context?.width`).
`request.path` starts as the track's `artwork` URL, which a `resolve` or a static `path` can replace; it's undefined only for a track with no artwork and nothing supplying a path, so guard it before signing (as above).
`resolveSync` / `transformSync` are no-Promise variants of `resolve` / `transform`. Reach for them when the per-track config or final tweak needs no `await` — a synced query param, a locally-computed path — to skip a Promise allocation per image (the example above is fully sync for that reason).
If you set *both* the sync and async form of the **same** stage (e.g. `transform` *and* `transformSync`), the async one runs first and the sync one tweaks its result; `resolve` and `transform` are independent stages that both always run.
::: tip Per-route artwork
A route can override the global `artwork` with its own config — `routes: { '/premium': { artwork: { baseUrl: '…' } } }` — so different content can load images from different hosts. On iOS and Android it applies to `artworkSource` and Android Auto browse rows; CarPlay rows, tabs and tiles use the global config, and so does the web implementation. See the [Browser](/guide/browser) guide.
:::
## SF Symbols (iOS)
Prefix `artwork` with `sf:` to render an Apple [SF Symbol](https://developer.apple.com/sf-symbols/) instead of fetching an image — ideal for tab and category icons.
Optional `bg` (background) and `fg` (symbol color) query params set the colors. On the lock screen and in `artworkSource`, `bg` defaults to transparent and `fg` to black. There the library renders the symbol to a PNG on device and caches it. CarPlay differs (below):
```ts
{
title: 'Favorites',
path: '/favorites',
artwork: 'sf:heart.fill?bg=#FF0090&fg=#fff'
}
```
On CarPlay rows and tiles the library draws the symbol on a grey tile.
With **no `fg`**, it draws black on light grey and white on dark grey, and CarPlay swaps them with the appearance; a `bg` alone is ignored. With an `fg`, the symbol is drawn in that color on `bg`, or on a grey tile when `bg` is omitted.
A tab icon is the exception: the symbol goes to CarPlay as is, `bg` and `fg` are ignored, and CarPlay tints it. This is iOS-only; on Android an `sf:` value is not a valid image.
## Tinting and platform icons
For monochrome **icons** (not full-color album art), let the system tint them to stay legible on either appearance:
* **iOS CarPlay** — declare [`style: { artworkRendering: 'stencil' }`](/api/types/browser-nodes/#trackstyle) on the track. Inside a page it's an inherited style property (a section- or page-wide value covers every item); tabs render without a section context, so a tab icon needs the declaration on the tab track itself.
CarPlay tints the glyph per appearance: black in light mode, white in dark.
* **Android Auto** is dark-only, so there's no per-appearance tinting — ship an appropriately colored (e.g. white) icon.
When a layout is declared (`display` on the section, page, or parent item), an `android.resource://…/drawable/…` artwork URI switches Android Auto to the **category** variant of that layout (which adds icon margins and lets Android Auto render it as an icon).
The library only sets the category style; the visual treatment is Android Auto's — see [Browse display](/guide/android-auto#browse-display).
```ts
{
title: 'Settings',
path: '/settings',
artwork: 'sf:gear',
style: { artworkRendering: 'stencil' }
}
```
**SVG** is detected by a `.svg` URL suffix: serve SVGs with a path ending in `.svg` and they decode as vectors rather than raster images.
On iOS that covers CarPlay browse rows, tabs and tiles, but not the lock screen or Control Center. On Android it covers Android Auto browse and the notification / now-playing image. Your own `` showing `artworkSource` needs its own SVG support.
## Light and dark artwork
Tinting recolors *one* image. When the two appearances need genuinely **different** images — a logo whose colors change, a mark with a light-on-dark counterpart — set `artwork` to an [`ArtworkVariants`](/api/types/browser-nodes/#artworkvariants) pair instead of a URL:
```ts
{
title: 'Playlists',
path: '/playlists',
artwork: {
light: 'https://images.example.com/playlists-light.png',
dark: 'https://images.example.com/playlists-dark.png'
}
}
```
Both fields are required — a pair with one side missing has no sensible fallback at render time.
On CarPlay browse rows and tabs the library fetches both and registers them as a single adaptive image, so switching appearance mid-drive swaps the image **in place** — no re-fetch, and no re-query of the browse tree.
Each URL runs through the [transform pipeline](#the-transform-pipeline) independently, so `baseUrl`, headers, `imageQueryParams` and `resolve` / `transform` apply to both.
Everywhere a single image is required, a pair resolves to its `dark` URL:
| Surface | Uses |
| ---------------------------------------- | ----------------------------- |
| **CarPlay browse rows / tabs** | both, adapting per appearance |
| **Android Auto** | `dark` |
| **Now-playing** (all platforms) | `dark` |
| **`artworkSource`** (your own ``) | `dark` |
::: tip Pair or tint?
Prefer [`artworkRendering: 'stencil'`](#tinting-and-platform-icons) when recoloring the same shape gives the right result: it's one fetch instead of two, the variants can't drift apart, and it works from the image's alpha so the source color is irrelevant. Reach for a pair only when the appearances need different artwork.
:::
::: warning Android Auto fetches only `http(s)` artwork
Browse artwork is served to Android Auto through an internal content provider that only fetches `http`/`https` URLs. `android.resource://` and `file://` URIs pass through and render directly; other custom schemes won't load there.
:::
## Now-playing artwork
By default the now-playing image (lock screen, Control Center, CarPlay / Android Auto Now Playing) is the active track's `artwork` — the same image as its browse-row thumbnail.
To resolve it differently, set `nowPlayingArtwork`, which builds the now-playing image from its **own** request. Like any artwork config, it can use an `{id}` template filled from the active track's `id`:
```ts
import { configureBrowser } from 'react-native-audio-browser'
configureBrowser({
nowPlayingArtwork: {
baseUrl: 'https://images.example.com',
// {id} is replaced with the active track's id
path: '/artwork/{id}',
// ask the CDN for a lock-screen-quality variant
imageQueryParams: { width: 'w', height: 'h' }
}
})
```
Now-playing surfaces request a **much larger** image than list thumbnails — on iOS, up to the screen width in pixels — so with `imageQueryParams` set you fetch a fittingly large variant rather than upscaling a tiny thumbnail.
If you *don't* set `nowPlayingArtwork` at all, now-playing surfaces fall back to the `artwork` config (and to `track.artwork`).
`nowPlayingArtwork` is an `ArtworkRequestConfig` like `artwork`, so it takes the same `resolve` / `transform` / `imageQueryParams`. It is **native-only**. On web, now-playing artwork is the track's own `artwork` URL as set (the `dark` URL of a pair), with neither `artwork` nor `nowPlayingArtwork` applied.
Artwork is also the one now-playing field the text layers can't touch — the formatter / override / flash carry only `title` / `artist` / `album`. See [Now Playing](/guide/now-playing#now-playing-artwork) for the metadata side.
::: warning Now-playing artwork follows the active track
Now-playing artwork is resolved **once per active track**, keyed on its `id` — so it won't re-resolve while the same track keeps playing.
There is no imperative way to swap *only* the image mid-stream: `updateNowPlaying()` overrides `title` / `artist` / `album`, not artwork.
Changing it means making a *new* active track (a different `id` plus the new `artwork`) the current one, which reloads playback — so it's not a fit for, say, updating live-radio cover art on each song. An in-place update API is tracked in [issue #76](https://github.com/radio-garden/react-native-audio-browser/issues/76).
:::
## Tile sections
A page's [`Section`](/api/types/browser-nodes/#section) can render its tracks as tappable artwork tiles by declaring `style: { display: 'grid' }` (wrapping; add `gridWrap: false` for a single line of tiles):
```ts
{
path: '/home',
title: 'Home',
sections: [
{
title: 'Featured',
style: { display: 'grid', gridWrap: false },
// header / "view all" target
path: '/browse/featured',
children: [
{
title: 'Jazz',
path: '/browse/jazz',
artwork: 'https://…/jazz.jpg'
},
{
title: 'Rock',
path: '/browse/rock',
artwork: 'https://…/rock.jpg'
}
]
}
]
}
```
Each tile is an ordinary Track, so its `artwork` runs through the same pipeline as any other. Tile styles presume artwork: a track without any renders as a placeholder tile plus its title — the artwork `resolve` hook is the place to supply fallback art.
See [Browser → Presentation](/guide/browser#presentation) for the full per-surface rundown.
## API summary
| Symbol | Purpose |
| --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| [`Track.artwork`](/api/types/browser-nodes/#track) | The image you set — `https` URL, `sf:` symbol (iOS), platform URI, or a `{ light, dark }` pair. |
| [`Track.artworkSource`](/api/types/browser-nodes/#track) | Output-only resolved `ImageSource` for your own ``. |
| [`TrackStyle.artworkRendering`](/api/types/browser-nodes/#trackstyle) | `'stencil'` tints a monochrome icon per CarPlay light/dark (iOS only). |
| [`ArtworkVariants`](/api/types/browser-nodes/#artworkvariants) | A `{ light, dark }` pair set on `artwork` when the appearances need different images. |
| [`artwork`](/api/types/browser/#artworkrequestconfig) | Config for browse-row image requests (and the default everywhere). |
| `nowPlayingArtwork` | Separate config for now-playing art; native-only. |
| [`imageQueryParams`](/api/types/browser/#imagequeryparams) | Map the surface's requested size to your CDN's query params. |
| [`ImageContext`](/api/types/browser/#imagecontext) | Requested `width`/`height` in pixels, passed to `transform`. |
| [`Section.style`](/api/types/browser-nodes/#sectionstyle) | `display: 'grid'` (± `gridWrap: false`) renders a section's tracks as artwork tiles. |
---
---
url: https://audiobrowser.dev/guide/errors.md
description: >-
Playback errors versus navigation errors: how each surfaces, what the
automatic retry budget does, and how to show an advisory error while it
retries.
---
# Errors
Two different things can fail, and they surface separately:
* **Playback errors** — a track or stream won't play. See
[Playback errors](#playback-errors).
* **Navigation errors** — browsing/resolving content failed (a route errored,
the network dropped, a server returned non-2xx). See
[Navigation errors](#navigation-errors).
For playback, the library can also **retry automatically** — transient failures
recover on their own, and while it retries the error is surfaced as *advisory*
so your UI can say what's wrong over the spinner. See
[Automatic retry](#automatic-retry).
The UI snippets import `View` / `Text` / `Button` from `react-native`; everything
else is from `react-native-audio-browser`.
## Playback errors
When the active track fails, the [playback state](/guide/playback#playback-state)
becomes `'error'` and a [`PlaybackError`](/api/features/errors/#playbackerror) is
available. Read it reactively with
[`usePlaybackError()`](/api/features/errors/#useplaybackerror) — it returns the
current error, or `undefined` once playback recovers.
`PlaybackError` is `{ kind, code, message, statusCode?, retrying? }`. **Branch
on `kind`**:
| Field | Use it for |
| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kind` | Everything user-facing. A normalized classification both platforms map onto — see the table below. |
| `code` | Diagnostics and telemetry **only**. Platform-specific and unstable: loader cases on iOS (`failed-to-load`, …), lower-cased ExoPlayer names on Android (`io-bad-http-status`, …). |
| `message` | Logs. Hard-coded developer English, e.g. *"Failed to load audio track"*. |
| `statusCode` | The HTTP status, when the failure came from a response. |
| `retrying` | `true` while [automatic retry](#automatic-retry) is still working on the failure — the error is advisory, not final. See [Errors while retrying](#errors-while-retrying). |
::: warning Don't show `message` to listeners
It is developer English and it is never localized. Map `kind` to your own copy
instead — the same error reaches the lock screen and the car, where a technical
string is especially jarring.
:::
`kind` is one of:
| `kind` | Meaning | Retrying help? |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
| `'offline'` | The device had no connection at the moment of failure. The stream may be fine. | Once back online |
| `'unreachable'` | The host could not be reached: DNS failure, refused connection, timeout, or a connection dropped while loading. | Maybe |
| `'not-found'` | The server said this stream is gone (HTTP 404 / 410). | No |
| `'rejected'` | The server refused the request: any HTTP 4xx other than 404 / 410 (auth, geo-blocking, rate limiting), or a DRM, licence or region refusal (Android and web). | No (except 408 / 429) |
| `'server-error'` | The server responded 5xx. Usually transient. | Maybe |
| `'unplayable'` | Fetched, but not playable: unknown container, unsupported codec, decoder failure. | No |
| `'stalled'` | Playback had started, then stopped, and the player exhausted its recovery budget. | Maybe |
| `'unknown'` | Could not be classified. Inspect `code`. | Maybe |
Codes that name no cause stay `'unknown'` rather than being guessed into a
friendlier bucket — a wrong classification misleads the listener *and* poisons
your telemetry aggregates.
Map `kind` to your own localized copy. How finely you split is a product
decision — collapsing several kinds onto one line is fine, as long as the
listener can still tell *"fix your connection"* from *"this one is gone"* from
*"try again in a minute"*:
```tsx
import { View, Text, Button } from 'react-native'
import { usePlaybackError, retry } from 'react-native-audio-browser'
import type { PlaybackErrorKind } from 'react-native-audio-browser'
function errorLine(kind: PlaybackErrorKind): string {
switch (kind) {
case 'offline':
return t('…your "check your connection" copy')
// Both transient — worth another try, so they can share a line.
case 'unreachable':
case 'server-error':
return t('…your "could not reach it" copy')
// Both refusals: a manual retry rarely helps (with automatic
// retry on, a 408 / 429 was already retried).
case 'not-found':
case 'rejected':
return t('…your "not available" copy')
case 'unplayable':
return t('…your "cannot be played" copy')
case 'stalled':
return t('…your "connection lost" copy')
case 'unknown':
return t('…your generic fallback copy')
}
}
function PlaybackErrorView() {
const error = usePlaybackError()
if (!error) return null
return (
{errorLine(error.kind)}
retry()} />
)
}
```
Leaving off the `default` case is deliberate: TypeScript then tells you when a
new `kind` is added, instead of it silently falling into a generic line.
Outside React, use `getPlaybackError()` for a snapshot or
[`onPlaybackError`](/api/features/errors/#onplaybackerror) to subscribe. The same
error is also passed to the [Now Playing formatter](/guide/now-playing#the-formatter-derived-continuous),
so you can show it on the lock screen / car too.
### Manual retry
[`retry()`](/api/features/playback/#retry) re-attempts the current item. It's
the action behind a "Try again" button, and what you call after
[automatic retry](#automatic-retry) has given up.
From `'error'` it begins a fresh load with fresh retry budgets, exactly as if
the listener had re-selected the track. A plain play command from `'error'`
does the same.
Call it from `'error'` only, because the platforms differ outside that state.
On Android and web it does nothing unless the player is in `'error'` or
stopped, where it reloads the item. On iOS it reloads the current item from
any state, even while it plays.
## Automatic retry
Configure [`setupPlayer({ retry })`](/api/features/player/#retryconfig) to
recover from transient **load** failures (network blips, timeouts, a live
stream dropping mid-play) with exponential backoff. It's **off by default**,
and it's native only — the web implementation has no automatic retry, so every
web error is terminal:
```ts
import { setupPlayer } from 'react-native-audio-browser'
// Retry with the default duration budgets (see below):
await setupPlayer({ retry: true })
// Or bound it yourself:
await setupPlayer({
retry: {
maxRetries: 5,
maxRetryDurationMs: 60_000,
firstConnectMaxRetryDurationMs: 8_000
}
})
```
Which failures qualify is nearly the same on iOS and Android. HTTP 408 and
429 qualify, and so do server errors: every 5xx on iOS, the common four (500,
502, 503, 504) on Android.
Transport failures qualify too (DNS, timeouts, a dropped connection), and so
does anything the platform couldn't classify, which is assumed transient
rather than fatal.
Permanent failures are never retried — 403 / 404, and media that can't be
parsed or decoded.
### Two duration budgets
Retry state is tracked per **load**: one track's playback session. A load is
created when a track becomes current (selection, queue advance, skip) *or is
restarted from a terminal error* (`retry()`, or any play command while in
`'error'`), and it survives every automatic retry of that track.
A new load starts fresh budgets.
How long the player keeps trying depends on one piece of evidence: **has this
load ever produced audio?**
| Situation | Budget | Why |
| --------------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **First connect** — the load has never played | `firstConnectMaxRetryDurationMs` after its first failure, default **12s** | A stream that fails before ever playing is usually dead, and the listener is actively waiting for a verdict — seconds, not minutes. |
| **Recovery** — any load | `maxRetryDurationMs` of silence, default **2 min** | Playback proved the stream works. Drops are usually transient (tunnels, network handovers, a station's encoder restarting) and patience recovers them unattended. |
**Silence** is time the listener wants audio and hears none. Only 5 s of audio
in a row ends it, so a stream that plays a moment between failures stays
silent, and a stream that closes every 10 s but plays in between keeps playing
however long it runs. The player gives up when the deadline passes, without
waiting for another failure.
While the device is **offline**, the first-connect budget does not apply: the
player makes no connection and connects the moment connectivity returns, so a
stream started in a tunnel still plays when the network comes back. Any offline
observation resets the first-connect clock, which only ever measures a
contiguous online stretch.
Time offline **counts** toward `maxRetryDurationMs`, so playback can't surprise
the listener by resuming after a long time offline.
After a connection that delivered audio, the player reconnects at once; after
one that delivered nothing, it waits 1 s, then 1.5, 2.25 and 3.375, capped at
5 s, starting at 1 s again once a connection delivers audio. Connections start
at least 1 s apart. `maxRetries` counts the connections in a row that delivered
nothing, so a stream that played and dropped reconnects once more than it.
On Android, a failure that media3 can resume within its connection, an HLS
segment or playlist and a file whose length the server declared, is retried in
place with the same backoff and keeps the buffered audio playing. It is not a
connection, so the rules above for connections don't hold for it: only the
duration budgets bound it, it keeps retrying every few seconds while offline,
it waits out its backoff once the network returns, and its loads can start
less than 1 s apart.
While it waits to reconnect, the player holds audio focus as it does while
playing. Another app taking the focus pauses it. A transient loss, a call
among them, holds the reconnect until the focus returns, then reconnects. At
the reconnect, the focus passes to the playing engine with a gap of a few
milliseconds: an app that asks for focus within it loses it again to the
reconnect, as it would to a tap on play.
Once a budget is exhausted the state lands on `'error'`, where your
`PlaybackErrorView` and [`retry()`](#manual-retry) take over.
Restarting from `'error'` — via `retry()` or any play command — begins a
**new load** of the same track: fresh budgets, starting with the
first-connect one. The tap behaves exactly like re-selecting the track.
### Errors while retrying
While the retry loop is working, the player doesn't go silent: each failure is
classified and surfaced immediately through
[`onPlaybackChanged`](/api/features/playback/#onplaybackchanged) /
[`usePlayback()`](/guide/playback#playback-state), attached to the current
non-terminal state (`'loading'` / `'buffering'`, or `'paused'`) with
`retrying: true`.
Show it as advisory — the cause over a spinner — because the next attempt may
still succeed. A 408 or 429 arrives here as `kind: 'rejected'` with
`retrying: true`; it becomes final only once retry gives up:
```tsx
const { state, error } = usePlayback()
if (error?.retrying) {
// Still trying: provisional copy, keep the spinner.
} else if (state === 'error') {
// Gave up: final copy, offer retry().
}
```
`onPlaybackError` and `usePlaybackError()` stay **terminal-only**: they fire on
*both* edges of the `'error'` state — entering it (with the error) and leaving
it (with `error: undefined`; the hook returns `undefined` again). Advisory
errors never pass through them.
The same advisory error also reaches the
[Now Playing formatter](/guide/now-playing#the-formatter-derived-continuous), so
the lock screen and the car can show it too.
Advisory emissions are deduplicated by **classification** (`kind`, plus the
HTTP status when there is one) — never by the raw native `message`.
The scope is the current advisory episode. Consecutive identical failures
within one retry sequence produce a single event rather than one per backoff
tick. The dedupe resets once the advisory clears: on recovery, a track change,
or hardening into the terminal error.
## Navigation errors
When resolving a browse path fails, a
[`NavigationError`](/api/features/errors/#navigationerror) is produced. Read the
raw error (with `code` and HTTP details) via
[`useNavigationError()`](/api/features/errors/#usenavigationerror), or subscribe
with `onNavigationError` / snapshot with `getNavigationError()`.
`NavigationError` is `{ code, message, statusCode?, statusCodeSuccess? }`, where
`code` is one of:
| `code` | Meaning |
| --------------------- | --------------------------------------------------------------------------------------------- |
| `'content-not-found'` | No route for the path, or the route returned no content (a config issue, not an HTTP 404). |
| `'network-error'` | The request failed (connection error, timeout, no internet). |
| `'http-error'` | Server returned non-2xx (or 2xx but parsing failed) — see `statusCode` / `statusCodeSuccess`. |
| `'callback-error'` | Your browse callback returned an error (e.g. auth/subscription required). |
| `'empty-content'` | The page has no tracks (empty Favorites, no search results). CarPlay / Android Auto only. |
| `'timeout'` | Resolution didn't finish in time. CarPlay only. |
| `'unknown-error'` | An unexpected error (e.g. invalid configuration). |
`'empty-content'` and `'timeout'` never reach `useNavigationError()` or
`onNavigationError`: the library raises them only for the in-car screens, where
they pass through [`formatNavigationError`](#showing-navigation-errors). Handle
them there.
### Showing navigation errors
For display, prefer
[`useFormattedNavigationError()`](/api/features/errors/#useformattednavigationerror)
— it returns a ready-to-show [`FormattedNavigationError`](/api/features/errors/#formattednavigationerror)
(`{ title, message? }`). Outside React, read it with
`getFormattedNavigationError()` or subscribe with
[`onFormattedNavigationError`](/api/features/errors/#onformattednavigationerror).
The **same** formatted error drives the CarPlay and Android Auto error dialogs,
so your in-app and in-car messages stay consistent:
```tsx
import { Text } from 'react-native'
import { useFormattedNavigationError } from 'react-native-audio-browser'
function BrowseError() {
const error = useFormattedNavigationError()
if (!error) return null
const detail = error.message ? ` — ${error.message}` : ''
return (
{error.title}
{detail}
)
}
```
Without configuration you get sensible English defaults. To localize or override
specific cases, set `formatNavigationError` in
[`configureBrowser`](/guide/browser) — return `defaultFormatted` for the cases
you don't want to change:
```ts
import { configureBrowser } from 'react-native-audio-browser'
configureBrowser({
formatNavigationError: ({ error, defaultFormatted, path }) => {
if (error.code === 'http-error') {
return {
title: 'Server error',
message: `Request failed (${error.statusCode})`
}
}
return defaultFormatted // keep the default for everything else
}
// ...tabs, routes
})
```
Use the raw `useNavigationError()` when you need to branch on `code` /
`statusCode`; use `useFormattedNavigationError()` when you just need a title and
message to render.
## API summary
| API | Purpose |
| ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `usePlaybackError()` / `getPlaybackError()` | The current playback error (`{ kind, code, message, statusCode?, retrying? }`) — branch on `kind`. |
| `onPlaybackError` | Subscribe to terminal playback errors outside React (fires on entering/leaving `'error'`; advisory retrying errors arrive via `onPlaybackChanged`). |
| `retry()` | Re-attempt the current item; meant for the `'error'` state (on iOS it reloads from any state). |
| `setupPlayer({ retry })` | Automatic retry with two [duration budgets](#two-duration-budgets): first-connect and recovery. Off by default. |
| `useNavigationError()` / `getNavigationError()` | The raw navigation error (`code`, `statusCode`, …). |
| `onNavigationError` | Subscribe to navigation errors outside React. |
| `useFormattedNavigationError()` / `getFormattedNavigationError()` | Display-ready `{ title, message? }`, shared with CarPlay / Android Auto. |
| `onFormattedNavigationError` | Subscribe to the formatted navigation error outside React. |
| `configureBrowser({ formatNavigationError })` | Customize / localize the formatted messages. |
---
---
url: https://audiobrowser.dev/guide/live-streams.md
description: >-
The map for live audio: stream formats, missing durations, dropped
connections, expiring URLs, song titles carried in-band, and Android's
periodic position updates.
---
# Live Streams
Live audio is what most of this player's edge cases are about: streams that
have no duration, drop in tunnels, expire their URLs, and carry their song
titles in-band.
The pieces live in their own guides — this page is the map,
with just enough of each to know which link you need.
## Stream formats
Point [`src`](/api/types/browser-nodes/#src) at the stream URL — there is
no format field; each platform's player detects the container:
* **HLS** (`.m3u8`) — iOS, Android and web. iOS and Android read in-band
ID3 timed metadata.
* **ICY / Icecast / Shoutcast** — plain HTTP radio, iOS, Android and web. On
iOS and Android the ICY `StreamTitle` arrives as timed metadata, filling
only `title`.
* **Progressive HTTP** — ordinary MP3/AAC/… files and endless streams, iOS,
Android and web.
* **DASH** — Android (bundled Media3 module) and web; iOS's AVPlayer doesn't
support it. **SmoothStreaming** is Android only.
Timed metadata of either kind reaches the lock screen only once your
[now-playing formatter](/guide/now-playing#the-formatter-derived-continuous)
applies it, never automatically (see
[Metadata](/guide/metadata#timed-metadata-the-live-song)).
Mark the track itself with [`live: true`](/api/types/browser-nodes/#live):
it arms [`seekToLiveEdge()`](#the-live-edge) on every platform, and gives
now-playing non-scrubbing controls on iOS and Android. On Android a cast
receiver also loads it as a live stream. On iOS it also shows the live
indicator, turns an end of stream or a stall into a reconnect at the live
edge, and skips saving a position. Declare it on every live track.
To hear it, put the track in the queue (or serve it from a
[browse tree](/guide/basic-usage)) after
[`setupPlayer()`](/guide/basic-usage#set-up-the-player) has run:
```ts
import { play, setQueue } from 'react-native-audio-browser'
setQueue([
{
src: 'https://stream.example.com/main.mp3',
title: 'Beacon FM',
live: true
}
])
play()
```
## Dropouts: stalls and retry
A connection drop mid-stream surfaces one of two ways, with different owners:
* **A stall** (how most iOS drops surface) — the player holds `'buffering'`
with play intent, and re-establishes the stream by itself when
connectivity returns (see
[Network → You may not need this](/guide/network#you-may-not-need-this)).
While stalled offline, the [now-playing formatter](/guide/now-playing#the-formatter-derived-continuous)
receives `stalled: 'offline'` (vs `'buffering'` when online) so the lock
screen can say why.
* **A playback error** (how most Android drops surface) — recovery belongs
to [automatic retry](/guide/errors#automatic-retry)
(`setupPlayer({ retry })`, off by default). Which of
[two duration budgets](/guide/errors#two-duration-budgets) applies depends
on whether this load has ever produced audio:
* **First connect**, for a stream that never played. Only online time
counts, so a station tapped in a tunnel still gets its chance when the
network returns.
* **Recovery**, once playback proved the stream works. This one is
wall-clock time and includes offline time, so playback never resumes by
surprise after a long outage.
Once the budget runs out, the state is `'error'`, and
[`retry()`](/guide/errors#manual-retry) and your error UI take over.
Android's reconnect-on-restore only arms through the retry machinery, so
the platform whose drops become errors is also the one that won't heal
without it. **If surviving tunnels matters to you, enable `retry`.**
The web implementation has no automatic retry at all, and no timed metadata,
neither ICY nor HLS ID3. Every web error is terminal.
## Fresh URLs on reconnect
If your stream URLs are signed or short-lived, build them in
[`media.resolve`](/guide/browser#media-and-artwork) — the per-track layer of
the stream request. When a reconnect re-runs it depends on the platform:
* **iOS** re-runs it on every reload: automatic retry, network restore,
play-from-`'error'` and a live-edge reconnect. A URL that expired during
the outage is re-signed instead of re-failing.
* **Android** reuses the URL it resolved, and re-runs `media.resolve` only
after an attempt to open that URL has failed. A URL that expired
mid-stream therefore costs one failed attempt.
With `retry` on, a status that retrying can't fix (a 401 or 403, say; see
[which failures qualify](/guide/errors#automatic-retry)) puts playback in
`'error'`, and the next [`retry()`](/guide/errors#manual-retry) or play
command re-resolves. With `retry` off, ExoPlayer's own few retries cover any
status, and the first of them re-resolves.
* **Web** re-runs it on every reload: play-from-`'error'` or after a stop,
`retry()` and a live-edge reconnect. Web has no automatic retry.
```ts
import { configureBrowser } from 'react-native-audio-browser'
// Merge `media` into your one configureBrowser call — it replaces the
// whole config, so a media-only call would drop your tabs and routes.
configureBrowser({
media: {
resolve: async (track) => ({
path: `/stream/${track.id}`,
// sign() is yours — however your backend mints stream tokens
query: { token: await sign(track.id) }
})
}
})
```
A relative `path` is joined to your configured `baseUrl` — see
[Shaping requests](/guide/browser#shaping-requests) for the layering.
## The live edge
[`seekToLiveEdge()`](/api/features/playback/#seektoliveedge) jumps a live
track back to the newest available audio — a no-op unless the current track
declares `live: true`.
On a stream with a seekable live window (HLS with a sliding window) it seeks
to the window's edge; on a non-seekable one (typical ICY radio) it
reconnects instead — a fresh connection *is* the live edge.
On iOS and web the reconnect re-runs `media.resolve`. On Android it reuses the
resolved URL, so an expired one re-resolves only after that first attempt
fails (see [Fresh URLs on reconnect](#fresh-urls-on-reconnect)).
General seeking is in [Playback](/guide/playback).
## Pausing a live stream
On iOS and Android, how a live track pauses depends on whether it can be
rewound.
A stream that can't be rewound holds no connection while paused or stopped.
That covers progressive (ICY/Icecast) radio, and live HLS whose seekable
window is under 30 seconds. Left open, a paused player goes on downloading
it (on macOS for as long as it stays paused), and a resume plays what it
buffered, behind the stream. So pause and stop close the connection. The
now-playing surfaces go on showing the track, paused, and play reconnects at
the live edge.
A stream with a seekable window of 30 seconds or more (HLS with a DVR window)
pauses as an on-demand track does. It keeps its position, and play resumes
from there. [`seekToLiveEdge()`](/api/features/playback/#seektoliveedge)
while paused moves it to the window's end. On iOS a paused one keeps what it
has buffered but loads no more than 10 seconds ahead, where it would otherwise
go on loading toward the live edge; on Android the buffer limit (`maxBuffer`)
bounds it. A shorter window doesn't count: a short pause would carry the
position out of it.
A live track loaded without play intent (`load` or `setQueue` without
`playWhenReady`) opens no connection. It stays `loading` for a second, so a
`play()` that follows connects at once, with no `paused` in between. With no
play by then it reports `paused`. On iOS this holds for a seekable window too,
since a window isn't known before the stream connects. On Android a live
track loaded or skipped to while paused still connects and buffers.
## Periodic position updates (Android)
While the player plays or loads, Media3's media session sends External
Surfaces the playback state again every 3 seconds: the notification, the lock
screen, Android Auto, Bluetooth, and Media3 controllers in other apps (a
watch, say). The update carries the current and buffered position, so a
surface that extrapolates the position corrects any drift.
A live track has no progress bar, so a drifting position never shows, and the
update only refreshes the state's timestamp. Android 16's Bluetooth service
logs each one as `tried to update with no new data`.
If your app plays only live streams, turn the update off with a literal
`false` in your app's manifest:
```xml
```
Every real change still reaches the surfaces at once: state, play and pause,
seeks, speed, Now Playing and the queue. Surfaces extrapolate an on-demand
position from the last state, so their progress bars keep moving. What stops
is the correction: a position that drifts with no state change (a Sonos
speaker that slips while it still reports playing, say) stays wrong on the
surfaces until the next change.
Leave it on, the default, if your app plays on-demand audio. The flag is
Android-only: iOS and web have no such update.
## API summary
| API | Purpose |
| ----------------------------------------------------------------- | ----------------------------------------------------------------------- |
| [`Track.live`](/api/types/browser-nodes/#live) | Declare a live track: iOS live indicator, arms the live edge. |
| [`seekToLiveEdge()`](/api/features/playback/#seektoliveedge) | Jump to the newest audio (no-op for non-live tracks). |
| [`setupPlayer({ retry })`](/guide/errors#automatic-retry) | Automatic retry with first-connect and recovery budgets. |
| [`retry()`](/guide/errors#manual-retry) | Restart from `'error'` with fresh budgets. |
| [`media.resolve`](/guide/browser#media-and-artwork) | Build the stream request — signed / short-lived URLs. |
| [`useOnline()`](/guide/network) | Connectivity for your own UI; playback reacts on its own. |
| [`PERIODIC_POSITION_UPDATES`](#periodic-position-updates-android) | Android manifest flag: stop the 3 s position update for live-only apps. |
---
---
url: https://audiobrowser.dev/guide/metadata.md
description: >-
Read the metadata coming out of the media as it plays: the live ICY or HLS
song, the static tags baked into a file, and chapter markers.
---
# Metadata
As a track plays, the player surfaces metadata it reads *from the media* — the
live "now playing song" of a radio stream, the tags embedded in an audio file,
and chapter markers. These arrive as three independent event streams:
* [`onTimedMetadata`](/api/features/metadata/#ontimedmetadata) — the live song
from a stream (ICY radio or HLS in-band ID3), changing as the broadcast does.
* [`onTrackMetadata`](/api/features/metadata/#ontrackmetadata) — the track's
static metadata: on iOS the file's own tags, read when it loads; on Android
the player's merged view of the Track and the file.
* [`onChapterMetadata`](/api/features/metadata/#onchaptermetadata) — chapter
markers with time ranges, for podcasts and audiobooks.
These are **read-only signals coming *in*** from the media — they don't change
what's displayed anywhere. It's up to you to do something with them: feed the
[Now Playing](/guide/now-playing) surfaces, render your own UI, or build a
chapter list.
Timed metadata also has a getter and a hook,
[`getTimedMetadata()`](/api/features/metadata/#gettimedmetadata) and
[`useTimedMetadata()`](/api/features/metadata/#usetimedmetadata), so a screen
that mounts mid-song still has the title. Track metadata and chapters are
subscription-only: you subscribe and keep the latest value yourself, as shown
below.
The UI snippets below import `useEffect` / `useState` from `react`, and `Text` /
`Button` / `FlatList` from `react-native`; those import lines are
omitted for brevity. Everything else comes from `react-native-audio-browser`.
## Subscribing
Every metadata event follows the same shape: `addListener` registers a callback
and returns a cleanup function that unsubscribes.
```ts
import { onTimedMetadata } from 'react-native-audio-browser'
const unsubscribe = onTimedMetadata.addListener((metadata) => {
console.log('now playing:', metadata.title)
})
// later:
unsubscribe()
```
Because the cleanup function is exactly what React's `useEffect` wants returned,
turning any of these into reactive state is a one-liner — see
[Holding metadata in state](#holding-metadata-in-state).
## Timed metadata: the live song
[`onTimedMetadata`](/api/features/metadata/#ontimedmetadata) delivers the
"now playing song" announced by a live stream. Two formats arrive through this
one event:
* **ICY** metadata — Shoutcast / Icecast HTTP radio.
* **In-band ID3** timed metadata — how **HLS** live streams (and some others)
carry the current song.
It fires each time the stream announces a new song, so the value changes
throughout a single track.
::: info iOS also fires it for a file's tags
On iOS, a file without chapter markers fires `onTimedMetadata` too. It fires
once on load for each metadata format the file carries (ID3, iTunes), with the
file's own tags: `title`, `artist`, `album` and so on.
The
[Now Playing formatter](/guide/now-playing#the-formatter-derived-continuous)
then gets them as `timedMetadata` for an on-demand file too. A formatter that
reads `timedMetadata.title` shows the file's title. Android fires it only for
metadata the media sends during playback.
:::
[`TimedMetadata`](/api/features/metadata/#timedmetadata) — every field optional:
| Field | Meaning |
| -------- | ------------------------------------------------ |
| `title` | The song title (often "Artist - Song" in ICY). |
| `artist` | The artist, when the stream sends it separately. |
| `album` | The album, when present. |
| `date` | A date string, when present. |
| `genre` | The genre, when present. |
::: warning ICY sends only a title
Shoutcast / Icecast (ICY) radio populates **only `title`** — typically a combined
`"Artist - Song"` string. `artist`, `album`, `date`, and `genre` stay `undefined`
for ICY; they're filled only by ID3 / HLS / file metadata. For a radio app,
parse `title` yourself rather than binding `metadata.artist`.
:::
This is the signal behind a live station's "now playing" line. To show it on the
lock screen / car, you usually don't subscribe here directly — you read it inside
the Now Playing formatter, which is re-invoked on every timed-metadata update.
See [Now Playing → the formatter](/guide/now-playing#the-formatter-derived-continuous).
For the live song in *your own* UI, use `useTimedMetadata()`. It returns the
last timed metadata of the current track, and `undefined` from a track change
until the new track's first update:
```tsx
function NowPlayingSong() {
const song = useTimedMetadata()
return {song?.title ?? 'Unknown'}
}
```
Outside React, `getTimedMetadata()` reads the same value.
## Track metadata: the track's static fields
[`onTrackMetadata`](/api/features/metadata/#ontrackmetadata) delivers a
track's static metadata. What it carries depends on the platform:
* **iOS** reads the file's own tags (ID3 on an MP3, the metadata atoms in an
MP4/M4A) when the player loads the asset. It fires once, and only if the file
has tags.
* **Android** reports the player's merged metadata. The Track's own fields
(`title`, `subtitle` as `artist`, `album`, `description`, `genre`, artwork)
win over the file's tags. Once the [Now Playing](/guide/now-playing) line is
rendered, its title, artist and album replace them.
The event fires again whenever that merged view changes: a new now-playing
line, new artwork, or stream metadata that fills a field the Track leaves
empty.
So on Android, `title` and `artist` are what you or your formatter set, not the
file's. On iOS, use it for on-demand content (podcast episodes, audiobooks,
downloaded files) whose tags you didn't set yourself.
[`TrackMetadata`](/api/features/metadata/#trackmetadata) is richer than the
timed shape. **Every field is an optional `string`:**
| Field | Meaning |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `title` | Track title. |
| `artist` | Track artist. |
| `albumTitle` | Album name. |
| `subtitle` | Secondary line. On Android, the now-playing artist line once it is rendered. |
| `description` | Long description / show notes. |
| `artworkUri` | Android only: the artwork URL the player publishes for the Track, not the file's embedded cover art. |
| `trackNumber` | Track number within the album. |
| `composer` | Composer credit. |
| `conductor` | Conductor credit. |
| `genre` | Genre. |
| `station` | Android only: the station name from a Shoutcast / Icecast stream's headers. |
| `mediaType` | Android only, usually unset: a Media3 `MEDIA_TYPE_*` constant, as a number string. |
| `creationDate` | iOS: the tag's date string (ID3 `TDRC`, the iTunes release date). Android: day and month only, as `DDMM` (or `DD` or `MM` alone), with no year. |
| `creationYear` | Creation year. On iOS, the first four characters of `creationDate` when there is no year tag. |
`compilation` and `url` are in the type but neither platform sets them. Neither
platform exposes a file's embedded cover art.
```tsx
import { onTrackMetadata, type TrackMetadata } from 'react-native-audio-browser'
function FileInfo() {
const [meta, setMeta] = useState()
useEffect(() => onTrackMetadata.addListener(setMeta), [])
if (!meta) return null
return (
<>
{meta.title} — {meta.artist}
{meta.description}
>
)
}
```
::: tip Mind the field names
Two traps when moving between the streams:
* **title vs title:** `TimedMetadata.title` is the *song* (changes during a live
stream). `TrackMetadata.title` is the *file's* title on iOS, and on Android
the Track's title or the now-playing title.
* **album vs albumTitle:** timed metadata uses `album`; track metadata uses
`albumTitle`. Neither carries the file's cover art. `TimedMetadata` has no
artwork field, and `TrackMetadata.artworkUri` is the Track's artwork as
Android publishes it.
:::
## Chapter metadata: podcast & audiobook chapters
[`onChapterMetadata`](/api/features/metadata/#onchaptermetadata) delivers the
full list of chapters for the current track as a
[`ChapterMetadata[]`](/api/features/metadata/#chaptermetadata):
| Field | Type | Meaning |
| ----------- | --------- | ------------------------------------------------------------------------------- |
| `startTime` | `number` | Chapter start, in **seconds**. |
| `endTime` | `number` | Chapter end, in **seconds**. |
| `title` | `string?` | Chapter title. Android falls back to the chapter's element ID (such as `chp0`). |
| `url` | `string?` | Android only: the chapter's URL link, if present. |
Because Android fills an untitled chapter with its element ID, the
`item.title ?? 'Chapter'` fallback below applies only on iOS.
Because `startTime` is in seconds, it drops straight into
[`seekTo`](/guide/playback#seeking) to make a tappable chapter list:
```tsx
import {
onChapterMetadata,
seekTo,
type ChapterMetadata
} from 'react-native-audio-browser'
function ChapterList() {
const [chapters, setChapters] = useState([])
useEffect(() => onChapterMetadata.addListener(setChapters), [])
return (
String(chapter.startTime)}
renderItem={({ item }) => (
seekTo(item.startTime)}
/>
)}
/>
)
}
```
## Which metadata is which
| | `onTimedMetadata` | `onTrackMetadata` | `onChapterMetadata` |
| ----------- | -------------------------------------------------------------------------- | ------------------------------------------------------------- | --------------------------- |
| Source | Live stream (ICY / ID3); on iOS also a file's tags | iOS: the file's tags. Android: the Track merged with the file | Chapter markers in the file |
| Changes | Throughout the track; on iOS also once on load for a file without chapters | iOS: once, on load. Android: whenever the merged view changes | Once, on load |
| Shape | One `TimedMetadata` | One `TrackMetadata` | A `ChapterMetadata[]` |
| Typical use | Live "now playing" song | Podcast/file info | Chapter navigation |
| Platform | iOS, Android | iOS, Android | iOS, Android |
::: warning Not available on web
All three are iOS and Android only. On web they are subscribable but never
fire, so a listener sees nothing and
[`FormatNowPlayingParams.timedMetadata`](/api/features/player/#formatnowplayingparams)
stays `undefined`.
ICY is the hard case: the browser strips the interleaved metadata before the
player can reach it, and no API exposes it. In-band ID3 from HLS *is* reachable
through the web player and simply isn't wired up yet — that part is tracked in
[#118](https://github.com/radio-garden/react-native-audio-browser/issues/118).
:::
## Holding metadata in state
Track metadata and chapters come with no built-in hook, but each `addListener`
returns the cleanup function `useEffect` expects, so a reusable hook is a few
lines:
```tsx
import {
onChapterMetadata,
type ChapterMetadata
} from 'react-native-audio-browser'
// Returns ChapterMetadata[] | undefined (undefined until the first event).
function useChapters(): ChapterMetadata[] | undefined {
const [chapters, setChapters] = useState()
useEffect(() => onChapterMetadata.addListener(setChapters), [])
return chapters
}
```
The same pattern works for `onTrackMetadata`: swap the event and the state type.
A hook built this way stays `undefined` until the next event, so a screen that
mounts after the file loaded sees nothing.
## API summary
| API | Delivers |
| ------------------- | -------------------------------------------------------------------------------------------- |
| `onTimedMetadata` | Live `TimedMetadata` (the streaming "now playing" song; on iOS also a file's tags, on load). |
| `onTrackMetadata` | `TrackMetadata` (iOS: the file's tags; Android: the Track merged with them). |
| `onChapterMetadata` | `ChapterMetadata[]` (chapter markers, times in seconds). |
All three are subscriptions: `addListener(cb)` returns an unsubscribe function.
`getTimedMetadata()` and `useTimedMetadata()` read the current timed metadata.
---
---
url: https://audiobrowser.dev/guide/now-playing.md
description: >-
What the system surfaces show: which metadata field lands where, the four
layers that decide its value at any moment, and reading the result back in
your own UI.
---
# Now Playing
The now-playing surface is everything that displays the current track on the *system's* surfaces: the iOS lock screen and Control Center, the Android notification, CarPlay and Android Auto's Now Playing screens, and Bluetooth head units.
The library publishes one metadata dictionary and the *operating system* renders it. Each surface picks different fields, composes them differently, and ignores the rest. Your own app can read the same metadata: see [Reading now-playing in your own UI](#reading-now-playing-in-your-own-ui).
This guide covers: **which fields land where** (the static matrix), **the four layers that decide what those fields contain at any moment** (the dynamic model), and **reading the result back** in your own UI.
## Which field shows where
Apple and Google document very little of this; the table below reflects observed behavior.
| Field | iOS lock screen / Control Center | CarPlay Now Playing | Android notification | Android Auto Now Playing | Bluetooth (AVRCP) |
| --------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------ | -------------------- | ------------------------ | ----------------------- |
| `title` | Primary line | Primary line | Primary line | Primary line | Title |
| `artist` | **Secondary line (sole source — `album` is never used as a fallback)** | Second line | Secondary line | Secondary line | Artist |
| `album` | Not shown | **Third line — also the tappable album/artist button (see below)** | Not shown | Rarely shown | Album (some head units) |
| `artwork` | Shown | Shown | Shown | Shown | — |
| `live` | "LIVE" indicator replaces the time scrubber | "LIVE" indicator | — | — | — |
The time scrubber (elapsed, duration, playback rate) is not driven by track fields at all — every surface derives it from the player itself. `Track.duration` is informational metadata for your app (echoed back through now-playing events); it does not affect the scrubber.
`artwork` is the URL you *set* on a track. On iOS and Android, surfaces show the resolved image, not the raw URL. On web, the Media Session gets the raw URL. The layers below cannot change it: see [Now-playing artwork](#now-playing-artwork).
## The four metadata layers
What actually renders is decided by a fixed priority order. Each layer only overrides the fields it sets. A field it leaves `undefined` falls through to the layer below, except under a flash (see [the flash](#the-flash-transient-top-priority)):
| Priority | Layer | API | Lifetime |
| ------------ | ---------------- | -------------------------------------- | ----------------------------------------------------------------------------------------- |
| 1 (highest) | **Flash** | `flashNowPlaying(update, durationMs)` | `durationMs`, on a native timer (web: see [the flash](#the-flash-transient-top-priority)) |
| 2 | **Formatter** | `setupPlayer({ nowPlaying })` | as long as it's configured |
| 3 | **Override** | `updateNowPlaying(update)` | until cleared or the track changes |
| 4 (baseline) | **Track fields** | `Track.title` / `artist` / `album` / … | the track's time as the active track |
### Track fields: the baseline
With nothing else configured, the active track's own fields are published as-is. For on-demand content this is usually all you need.
### The formatter: derived, continuous
The [`nowPlaying`](/api/features/player/#formatnowplayingcallback) formatter hands you the now-playing text lines outright. The library calls it again whenever the lines could change:
* on a track change
* on every timed-metadata update
* on every playback transition: play / pause, a stall starting or recovering, an error
* on connectivity changes
It's the right layer for anything *derived from playback state*: the live song from ICY/ID3 metadata, a "Reconnecting…" line during a stall, an error message:
```ts
setupPlayer({
nowPlaying: ({ timedMetadata, playWhenReady, stalled, error }) => {
// `yourErrorLine` is your own kind→copy mapping. Branch on
// `error.kind`, never `error.message`, which is developer English
// and never localized.
// This line is read by listeners, on the lock screen and in the car.
// See [Playback errors](/guide/errors#playback-errors).
if (error) return { artist: yourErrorLine(error.kind) }
if (stalled) {
return {
artist: stalled === 'offline' ? 'No connection' : 'Reconnecting…'
}
}
// The live song, only while actually playing — a paused stream's last
// song is stale, so fall back to the track default (return undefined).
if (!playWhenReady || !timedMetadata?.title) return
return { artist: timedMetadata.title }
}
})
```
The callback receives a single [`FormatNowPlayingParams`](/api/features/player/#formatnowplayingparams) object:
| Field | Type | Meaning |
| --------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `track` | `Track` | The currently playing track. |
| `timedMetadata` | `TimedMetadata?` | The ICY / ID3 "now playing song", if any. On iOS, also a file's own tags when the file has no chapters. |
| `playWhenReady` | `boolean` | Play/pause intent — stays `true` through buffers, so the song line won't flicker. |
| `stalled` | `StallReason?` | Truthy only during a mid-stream stall: `'buffering'` (rebuffering while online) or `'offline'` (no connectivity). Use `if (stalled)`, compare `=== 'offline'` for the reason. |
| `error` | `PlaybackError?` | The current playback error, if playback failed. Switch on `error.kind` to pick your own localized line: see [Playback errors](/guide/errors#playback-errors). |
While [automatic retry](/guide/errors#automatic-retry) is still working, `error` carries the advisory error (`error.retrying === true`). The formatter runs again when that error arrives, changes and clears. So you can show provisional copy ("Retrying…") that becomes the final line when the player gives up.
It returns a [`NowPlayingUpdate`](/api/features/metadata/#nowplayingupdate) (`{ title?, artist?, album? }`) or `undefined`. The callback is synchronous and should stay cheap: a pure formatting function, no I/O.
Each returned field falls back **independently** to the track's value when omitted. Returning `undefined` (or `{}`) uses the track default entirely. Identical results across a rapid burst of transitions are de-duplicated natively, so they won't flicker the surface.
Timed metadata is never auto-applied: the library surfaces ICY (Shoutcast/Icecast) and in-band ID3 (HLS) frames to your code, and the formatter is where you decide what reaches the now-playing line. (To consume those frames outside the formatter, subscribe to [`onTimedMetadata`](/api/features/metadata/#ontimedmetadata).)
### The override: imperative, sticky
[`updateNowPlaying({ artist: '…' })`](/api/features/nowPlaying/#updatenowplaying) pins fields until you pass `null` or the track changes. It's the layer to reach for when you *don't* configure a formatter.
**If a formatter is configured, it outranks the override.** The formatter's result is applied on top, falling back per-field to `override ?? track`. With a formatter in place, feed it state instead of calling `updateNowPlaying` around it. Prefer the formatter for anything derived from playback state.
### The flash: transient, top priority
[`flashNowPlaying(update, durationMs)`](/api/features/nowPlaying/#flashnowplaying) is the toast of the now-playing world: it briefly replaces the fields it sets, then reverts to whatever the lower layers say.
External surfaces have no notification primitive, so a transient metadata swap is the only way to give feedback there. The canonical use is answering a refused remote command:
```ts
// A radio product with an hourly skip allowance:
handleRemoteNext(() => {
if (skipsRemaining() > 0) {
skipToNext()
} else {
flashNowPlaying({ artist: 'Skip limit reached' }, 3000)
}
})
```
Three properties make it a dedicated layer rather than sugar over `updateNowPlaying`:
* **It outranks the formatter.** While a flash is active the formatter pass is skipped, so a live station's next metadata tick can't overwrite the message mid-window. Fields the flash leaves unset come from the override or the track, not from the formatter. Set every line you want to keep.
* **The revert runs on a native timer.** A JS `setTimeout` pauses with a backgrounded host on Android — and remote commands from the lock screen arrive exactly when the host is backgrounded. The native timer fires regardless.
* **A track change clears it early.** A flash is feedback about a moment; it never carries over to a new track.
Repeated calls restart the window. [`clearNowPlayingFlash()`](/api/features/nowPlaying/#clearnowplayingflash) cancels one imperatively — for example when the condition the flash complained about resolves mid-window.
::: warning Web and `nowPlaying: false`
The three properties above hold on iOS and Android. On web, a flash is an `updateNowPlaying` override with a JS timer. It replaces any override you set, and the revert (or `clearNowPlayingFlash()`) clears the override instead of restoring it.
A track change doesn't cancel the timer, so a pending revert also clears an override you set for the next track.
With `nowPlaying: false`, Android ignores the flash, while iOS still shows it.
:::
## Reading now-playing in your own UI
The metadata you publish is also what your own app should render — a mini-player, a full-screen "now playing" view — so the in-app UI matches the lock screen exactly, formatter and all. Use the [`useNowPlaying`](/api/features/nowPlaying/#usenowplaying) hook:
```tsx
import { Text } from 'react-native'
import { useNowPlaying } from 'react-native-audio-browser'
function MiniPlayer() {
const nowPlaying = useNowPlaying()
if (!nowPlaying) return null
return (
{nowPlaying.title} — {nowPlaying.artist}
)
}
```
`useNowPlaying` returns the resolved [`NowPlayingMetadata`](/api/features/metadata/#nowplayingmetadata): the same dictionary the system surfaces see, *after* the four layers are applied. The exception is `nowPlaying: false` on iOS and Android: the hook still reports an `updateNowPlaying` override the surface ignores (on Android, a flash too). It returns `undefined` when there is no active track. It carries `title` / `artist` / `album` / `artwork`.
It also carries `elapsedTime`, but only on iOS, and it is not a live position. For the scrubber position, use [`useProgress`](/guide/playback#progress).
Outside React, [`getNowPlaying()`](/api/features/nowPlaying/#getnowplaying) reads a snapshot. [`onNowPlayingChanged`](/api/features/nowPlaying/#onnowplayingchanged) fires whenever the published lines change: a new track, a formatter result, an override, or a flash starting or ending.
To render artwork, don't use this `artwork` field: it is a plain URL string, and on Android and web it is the track's `artwork` before your artwork config resolves it. Use the active track's `artworkSource` (` `). See [Track](/guide/track).
## Gotchas worth knowing
**CarPlay's tappable line renders from `album`.** When a track has an `albumPath` (or `resolveAlbumPath` returns a path), the *album line* becomes tappable. It renders as a third metadata line with a chevron and navigates the browse stack.
A track without an `album` has no such line, so there is nothing to tap even though a destination exists. See the [CarPlay guide](/guide/carplay#album-line-navigation).
**The iOS lock screen never shows `album`.** Its secondary line comes from `artist` alone. If you move information from `artist` to `album` (for example to feed the CarPlay button line), it disappears from the lock screen.
**`artist` and `album` render as adjacent lines on CarPlay.** Giving both the same string displays it twice. If both fields must carry related context (a live stream's location, say), differentiate the copy — the album line reads well as an action since it can be tappable.
**One metadata dictionary feeds every surface.** There is no per-surface metadata: whatever you publish appears (or doesn't) everywhere simultaneously, per the table above. You cannot hide a field from one surface without hiding it from all of them.
**A formatter quietly disables `updateNowPlaying` for the fields it returns.** See [the override](#the-override-imperative-sticky): the formatter's result wins per-field. If a line you set imperatively keeps reverting, a formatter is overwriting it; either move that logic into the formatter or use `flashNowPlaying` if it was meant to be transient.
**Browse lists are separate.** `subtitle` drives browse-list rows (CarPlay list detail text, Android Auto list subtitle) and is never shown on now-playing surfaces; `artist` drives now-playing and is never shown in browse lists. Neither falls back to the other.
## Now-playing artwork
Artwork is the one surface field the text layers (formatter / override / flash) can't touch: they carry only `title` / `artist` / `album`. On iOS and Android, surfaces show the active track's resolved artwork, `artworkSource`. That is the track's `artwork` after your [artwork configuration](/guide/browser#media-and-artwork) transforms it. On web, the Media Session gets the track's raw `artwork` URL (the `dark` one of a pair), which neither artwork config touches.
By default that's the same image as the track's browse-list thumbnail. To resolve it differently, set the `nowPlayingArtwork` config kind. It builds the now-playing image from its own request (e.g. `{ path: '/artwork/{id}' }`), for example a larger, lock-screen-quality image that does not bloat list thumbnails:
```ts
configureBrowser({
nowPlayingArtwork: { path: '/artwork/{id}' }
// ...tabs, routes
})
```
See [`BrowserConfiguration.nowPlayingArtwork`](/api/types/browser/#browserconfiguration).
## API summary
| API | Purpose |
| ----------------------------------------- | ----------------------------------------------------------- |
| `setupPlayer({ nowPlaying })` | Configure the formatter: derived lines from playback state. |
| `updateNowPlaying(update \| null)` | Imperatively override fields; `null` clears. |
| `flashNowPlaying(update, durationMs)` | Transient, top-priority swap (refused-command feedback). |
| `clearNowPlayingFlash()` | Cancel an active flash early. |
| `useNowPlaying()` / `getNowPlaying()` | Read the resolved metadata in your own UI. |
| `onNowPlayingChanged` | Subscribe to metadata changes outside React. |
| `onTimedMetadata` | Subscribe to ICY / ID3 stream metadata directly. |
| `configureBrowser({ nowPlayingArtwork })` | Resolve now-playing artwork from its own request. |
---
---
url: https://audiobrowser.dev/guide/playback.md
description: >-
Control the active track — play, pause, stop, seek, playback state, progress,
rate, and volume — and how playback handles the background, interruptions, and
audio focus.
---
# Playback
This guide covers **controlling the active track** — transport (play / pause /
stop), seeking, playback state, progress, rate, and volume. It's the toolkit for
building your own player UI.
[A later section](#background-audio-interruptions-and-audio-focus) covers what
the library handles for you: background audio, interruptions, and audio focus.
Playback acts on whatever the **active track** is. *Which* track that is — and
moving between tracks with next/previous — belongs to the
[queue](/guide/queue#moving-between-tracks);
this page is about playing the one that's already active. The system surfaces
(lock screen, notification, car) are covered in [Now Playing](/guide/now-playing).
> All functions here are synchronous. Called with no track loaded, they don't
> throw: `pause`, `stop` and the seek calls do nothing, and `setPlayWhenReady`,
> `setRate` and `setVolume` keep their value for the next track. `play()` and
> `togglePlayback()` raise the play intent as `setPlayWhenReady(true)` does, so
> the next track loaded starts playing (on web, Chrome keeps that intent and
> Firefox drops it). On iOS and Android, play, pause, stop, seek, rate and
> volume calls made before `setupPlayer` has resolved are dropped; on web they
> throw `SetupNotCalledError`. On every platform `setPlayWhenReady` is kept and
> applied at setup. Two have argument rules: `setRate` and
> `trackPlaybackTime`, both covered below.
The UI snippets below import `useState` from `react`, `Text` / `Button` /
`Switch` from `react-native`, and `Slider` from
`@react-native-community/slider`; those import lines are omitted for brevity.
Everything else comes from `react-native-audio-browser`.
## Transport controls
```ts
import { play, pause, togglePlayback, stop } from 'react-native-audio-browser'
play() // play or resume the active track
pause() // pause, keeping position
togglePlayback() // flip between play and pause
stop() // stop; the track stays loaded
```
`stop` keeps the track loaded, and what `play()` does afterwards depends on the
platform. On iOS, `stop` rewinds a non-live track to the start, so `play()`
plays it from the beginning. On Android and web the position is kept, so
`play()` resumes where it stopped.
`stop` is not the same as `reset`, which stops playback **and clears the queue**:
```ts
import { reset } from 'react-native-audio-browser'
reset() // tear down: stop + empty the queue
```
| | Position | Track stays loaded | Queue |
| --------- | ---------------------------------------------- | ------------------ | ------- |
| `pause()` | kept | yes | kept |
| `stop()` | reset to start on iOS; kept on Android and web | yes | kept |
| `reset()` | — | no | cleared |
## Seeking
Seek within the active track by an absolute position or a relative offset, both
in **seconds**:
```ts
import { seekTo, seekBy } from 'react-native-audio-browser'
seekTo(90) // jump to 1:30
seekBy(30) // skip ahead 30s
seekBy(-15) // back 15s
```
For live streams, jump back to the live edge (a no-op for non-live tracks):
```ts
import { seekToLiveEdge } from 'react-native-audio-browser'
seekToLiveEdge()
```
Moving between tracks (next / previous / skip) is part of the
[queue](/guide/queue#moving-between-tracks), not seeking.
## Playback state
`usePlayback` returns the current `{ state, error }`. The `state` is one of:
| State | Meaning |
| ------------- | ---------------------------------------------- |
| `'none'` | Idle — no track loaded (initial state). |
| `'loading'` | Loading the item before playback can begin. |
| `'ready'` | Track loaded and ready, currently paused. |
| `'playing'` | Currently playing. |
| `'buffering'` | Loading more data before it can continue. |
| `'paused'` | Paused. |
| `'stopped'` | Stopped. |
| `'ended'` | Reached the end of the queue. |
| `'error'` | Playback failed — see [Errors](/guide/errors). |
```tsx
import { usePlayback, retry } from 'react-native-audio-browser'
function PlayerStatus() {
const { state } = usePlayback() // `error` is also here — see Errors
if (state === 'error') {
return retry()} />
}
return {state}
}
```
`retry()` is meant for the `'error'` state, where it re-attempts the current
item. It isn't gated on that state.
On iOS it reloads the current item in any state, even while playing. On Android
and web it reloads whenever the player is stopped or failed, without raising the
play intent, so after `stop()` it loads the track but doesn't play it. See [Errors](/guide/errors#manual-retry) for the
error shape and handling.
### Just playing or buffering?
For a play/pause button, drive it off `usePlayingState` — not
`state === 'playing'` — so it isn't thrown off by the `loading`/`buffering`
states. It gives you two booleans and re-renders only when they flip:
```tsx
import { usePlayingState, togglePlayback } from 'react-native-audio-browser'
function PlayPauseButton() {
const { playing, buffering } = usePlayingState()
return (
togglePlayback()}
/>
)
}
```
### Play-when-ready
`playWhenReady` is the **intent** to play, separate from whether audio is
actually coming out yet (it may still be loading or buffering). Setting it does
what `play()` / `pause()` do, with two exceptions. Before `setupPlayer`
resolves, `setPlayWhenReady` is kept and applied at setup, while `play()` is
dropped on iOS and Android and throws on web.
On Android, `setPlayWhenReady(true)` doesn't restart a stopped or failed player;
`play()` or `retry()` does:
```tsx
import { setPlayWhenReady, usePlayWhenReady } from 'react-native-audio-browser'
setPlayWhenReady(true) // raise the intent to play
function PlayToggle() {
const wantsToPlay = usePlayWhenReady()
return (
setPlayWhenReady(next)}
/>
)
}
```
`usePlayWhenReady` is the raw intent: it stays `true` after an error.
`usePlayingState().playing` is that intent only while a
track can play, so it goes `false` in the `'error'`, `'ended'`, `'none'` and
`'stopped'` states.
Both flip the instant the user taps. Neither says whether
sound is coming out yet; `buffering` does.
## Progress
Progress is `{ position, duration, buffered }`, all in seconds. There are two
hooks, and the difference matters:
* **`usePolledProgress(intervalMs?)`** — polls on a timer (default 1000 **ms**).
Works out of the box, and automatically pauses while the app is backgrounded.
**Start here.**
* **`useProgress()`** — driven by native progress events. These are
**disabled by default** (`progressUpdateEventInterval` is `null`), so this
hook won't update until you turn them on (see below).
> **Mind the units.** `usePolledProgress` takes its interval in
> **milliseconds**; `progressUpdateEventInterval` (below) is in **seconds**.
```tsx
import { usePolledProgress, seekTo } from 'react-native-audio-browser'
function Scrubber() {
const { position, duration } = usePolledProgress()
return (
seekTo(seconds)}
/>
)
}
```
To use the event-based `useProgress` instead, enable progress events once at
setup by setting how often they fire (in seconds):
```ts
import { setupPlayer } from 'react-native-audio-browser'
await setupPlayer({ progressUpdateEventInterval: 0.5 })
// or later: updateOptions({ progressUpdateEventInterval: 0.5 })
```
Outside React, `getProgress()` returns a one-off snapshot of the current
position/duration/buffered — it's a plain getter and is **never** gated, so it
works even with progress events off. Only the `onProgressUpdated` event (and
therefore `useProgress`) depends on `progressUpdateEventInterval`.
## Playback rate
Rate is a multiplier: `1` is normal, `0.5` half speed, `2` double. Handy for
podcasts and audiobooks:
```ts
import { getRate, setRate } from 'react-native-audio-browser'
setRate(1.5) // 1.5× speed
getRate() // → current rate
```
Rate is a speed multiplier, not a transport control: it's independent of
play/pause, and setting it while paused doesn't start playback.
Pass a value
greater than zero — the platforms disagree on what a non-positive rate does
(iOS ignores it, Android throws, web stalls the audio element), so treat it as
unsupported rather than as a way to pause.
There's no reactive hook for rate (it only changes when you set it), so a
control that displays the current speed just holds it in local state:
```tsx
function SpeedControl() {
const [rate, setRateState] = useState(() => getRate())
const cycle = () => {
const next = rate >= 2 ? 0.5 : rate + 0.5
setRate(next) // tell the player
setRateState(next) // update the label
}
return
}
```
## Volume
There are two distinct volumes:
* **Player volume** — this player's own level, `0`–`1`. Use it for in-app
controls, ducking, or fades.
* **System volume** — the device's media volume, `0`–`1`.
Player volume has no reactive hook (it only changes when you set it), so a
controlled `` holds the value in local state — seed it from `getVolume()`
and write through to `setVolume`:
```tsx
import { getVolume, setVolume } from 'react-native-audio-browser'
function VolumeSlider() {
const [volume, setVolumeState] = useState(() => getVolume())
return (
{
setVolume(next) // apply to the player
setVolumeState(next) // keep the slider in sync
}}
/>
)
}
```
System volume *does* have a hook, since the hardware buttons can change it
behind your back:
```tsx
import { useSystemVolume } from 'react-native-audio-browser'
function SystemVolumeLabel() {
const volume = useSystemVolume() // re-renders on hardware volume keys
return {Math.round(volume * 100)}%
}
```
`setSystemVolume` is a **no-op on iOS** — Apple provides no public API to set
the system volume (use the player volume there instead). Reading it and
`useSystemVolume` work on iOS and Android. On web, `setSystemVolume` does
nothing, and `getSystemVolume` and `useSystemVolume` always return `1`.
## Measuring listening time
`trackPlaybackTime` calls you back every N seconds of **actual playback** — the
clock advances only while the state is `'playing'` and freezes on
pause/buffering/stop, so paused time never inflates the count. It's built for
"still listening" analytics pings:
```ts
import { trackPlaybackTime } from 'react-native-audio-browser'
// Fire every 30 seconds of real listening. `sendHeartbeat` is your own
// analytics call. The callback also gets `sinceLast` (seconds since the
// previous fire) if you'd rather report deltas than the running total.
const cancel = trackPlaybackTime(({ total, sinceLast, track }) => {
sendHeartbeat({ seconds: total, trackId: track?.id })
}, 30)
// later:
cancel()
```
`period` must be `>= 1` (it throws otherwise). On Android, subscribe after
`setupPlayer` has resolved. A subscription made earlier never fires, even once
the player is up, and neither does one that was active while the playback
service restarted. To get ticks again, cancel every subscription and subscribe
once more.
`total` counts from when you subscribed, across every track that plays: it
keeps climbing through track changes. To measure per track, cancel and
re-subscribe whenever the [active track changes](/guide/queue#the-active-track). It's a coarse,
\~1-second-resolution signal, not a precise timer.
`track` is the active track as of the latest track change since the first
`trackPlaybackTime` subscription. If the first subscription starts while a track
is already playing, it is `undefined` until the next track change.
## Background audio, interruptions and audio focus
Playback carries on with your app in the background and the screen locked:
* **iOS** needs the `audio` background mode in your app's `Info.plist` (see
[Getting Started](/guide/getting-started#installation)). The audio session
category defaults to `'playback'`; `ios.category`, `categoryMode`,
`categoryOptions` and `categoryPolicy` change it at setup
([iOS options](/guide/configuration#ios-options-ios)).
* **Android** plays from the library's foreground media service, which its
merged manifest declares. What happens when the app is swiped away is set by
`android.appKilledPlaybackBehavior`
([Android options](/guide/configuration#android-options-android)).
On iOS, the library activates the audio session when playback starts (on
`play()`, not at setup), so launching your app doesn't stop other apps' audio. It releases the
session about 3 seconds after playback stops, so their audio can come back.
**Interruptions** (a phone call, an alarm, another app starting audio) are
handled natively, with nothing to wire up:
* On **iOS**, an interruption pauses playback. When it ends, playback resumes
if iOS says it should and the player was playing when it began; otherwise it
stays paused.
* On **Android**, the player holds audio focus. It pauses while another app
holds focus briefly and resumes when focus returns. It pauses when another
app takes focus for good. It lowers its volume under a short sound such as a
notification, or pauses instead with `android.audioContentType: 'speech'`.
When the output disappears (headphones unplugged, a Bluetooth speaker switched
off), playback pauses; see
[Audio Output](/guide/audio-output#you-may-not-need-this-for-unplug-handling).
On Android, `android.handleAudioBecomingNoisy: false` turns that off.
## API summary
| API | Purpose |
| ----------------------------------------------- | ----------------------------------------------------------------------- |
| `play()` / `pause()` / `togglePlayback()` | Start, pause, or flip playback. |
| `stop()` | Stop; track stays loaded (position resets to the start on iOS only). |
| `reset()` | Stop **and** clear the queue. |
| `seekTo(seconds)` / `seekBy(offset)` | Seek to an absolute / relative position. |
| `seekToLiveEdge()` | Jump to the live edge (no-op if not live). |
| `usePlayback()` / `getPlayback()` | Full `{ state, error }`; subscribe via `onPlaybackChanged`. |
| `retry()` | Re-attempt the current item; meant for the `'error'` state. |
| `usePlayingState()` / `getPlayingState()` | `{ playing, buffering }` booleans for a play/pause button. |
| `onPlayingState` | Subscribe to `{ playing, buffering }` changes. |
| `setPlayWhenReady(bool)` / `usePlayWhenReady()` | Play/pause *intent*, independent of buffering. |
| `getPlayWhenReady()` / `onPlayWhenReadyChanged` | Read or subscribe to the play/pause intent. |
| `usePolledProgress(intervalMs?)` | `{ position, duration, buffered }` via polling (ms) — works by default. |
| `useProgress()` / `onProgressUpdated` | Progress via events (enable `progressUpdateEventInterval` first). |
| `getProgress()` | One-off progress snapshot; always works. |
| `getRate()` / `setRate(rate)` | Playback speed multiplier (`1` = normal). |
| `getVolume()` / `setVolume(0..1)` | This player's volume. |
| `getSystemVolume()` / `useSystemVolume()` | Device media volume (`setSystemVolume` does nothing on iOS or web). |
| `onSystemVolumeChanged` | Subscribe to device media volume changes. |
| `trackPlaybackTime(cb, period)` | Heartbeat every `period` seconds of real playback. |
---
---
url: https://audiobrowser.dev/guide/queue.md
description: >-
Build and edit the queue, move between tracks with next and previous, and read
it back for an "up next" UI.
---
# Queue
The **queue** is the ordered list of tracks the player works through. The track
at the current position is the **active track**: what plays, and what
next/previous move between. This guide covers building the queue, editing it,
moving between tracks, and reading it back for an "up next" UI.
For the first-time setup and the browse-tree concept, see
[Basic Usage](/guide/basic-usage#the-queue). For transport (play / pause / seek
*within* the active track), see [Playback](/guide/playback). The system
surfaces (lock screen, car) are in [Now Playing](/guide/now-playing).
The UI snippets below import `View` / `Text` / `Button` / `FlatList` from
`react-native`; those import lines are omitted for brevity. Everything else
comes from `react-native-audio-browser`.
## Setting the queue
[`setQueue`](/api/features/queue/#setqueue) replaces the entire queue.
Optionally pass which track to make active and where to start it:
```ts
import { setQueue, play } from 'react-native-audio-browser'
setQueue(tracks, 0) // replace; first track becomes active
setQueue(tracks, 2) // start on index 2
setQueue(tracks, 2, 30) // ...30 seconds in
```
On iOS and Android, `startIndex` defaults to 0. iOS clamps an index outside
the queue to its first or last track, and Android throws. On the web, an
omitted or out-of-range `startIndex` leaves no track active, so pass one (0 for
the first track).
`setQueue` doesn't start playback. On iOS and Android it keeps the current
play/pause state; on the web it stops playback. Either way, call
[`play()`](/api/features/playback/#play) after it (see
[Playback](/guide/playback)):
```ts
setQueue(tracks, 0) // or setQueue(tracks, startIndex)
play() // start playback
```
## Reading the queue
[`useQueue`](/api/features/queue/#usequeue) returns the current
[`Track[]`](/api/types/browser-nodes/#track) and re-renders whenever it changes
(add, remove, reorder, or metadata update):
```tsx
import { useQueue } from 'react-native-audio-browser'
function QueueList() {
const queue = useQueue()
return (
track.id ?? String(i)}
renderItem={({ item }) => {item.title} }
/>
)
}
```
Outside React, read a snapshot with
[`getQueue()`](/api/features/queue/#getqueue), or a single entry with
[`getTrack(index)`](/api/features/queue/#gettrack) (returns `undefined` if the
index is empty). To react to changes without a hook, subscribe to
[`onQueueChanged`](/api/features/queue/#onqueuechanged) — it fires with the new
queue on every add, remove, or reorder.
A favorite toggle also fires it on iOS
and Android, but on web it fires only
[`onFavoriteChanged`](/api/features/favorites/#onfavoritechanged), so listen to
both, as `useQueue` does.
## The active track
[`useActiveTrack`](/api/features/queue/#useactivetrack) returns the currently
playing [`Track`](/api/types/browser-nodes/#track) (or `undefined` when nothing
is loaded):
```tsx
import { useActiveTrack } from 'react-native-audio-browser'
function NowPlaying() {
const track = useActiveTrack()
return {track?.title ?? 'Nothing playing'}
}
```
Outside React, use [`getActiveTrack()`](/api/features/queue/#getactivetrack) and
[`getActiveTrackIndex()`](/api/features/queue/#getactivetrackindex). To react to
*changes* — e.g. for per-track analytics — subscribe to
[`onActiveTrackChanged`](/api/features/queue/#onactivetrackchanged), which also
reports the track you're leaving:
```ts
import { onActiveTrackChanged } from 'react-native-audio-browser'
const unsubscribe = onActiveTrackChanged.addListener((event) => {
console.log('now playing', event.track?.title)
console.log('left off', event.lastTrack?.title, 'at', event.lastPosition)
})
```
## Moving between tracks
Jump to a track by index, or step to the next/previous one. Each optionally
takes a start position **in seconds**:
```ts
import { skip, skipToNext, skipToPrevious } from 'react-native-audio-browser'
skip(3) // jump to index 3
skipToNext() // next track
skipToPrevious() // previous track
skipToNext(10) // next track, starting 10 seconds in
```
On iOS and Android, if there is no next (or previous) track, the position
still applies: the active track seeks to it. On the web the call does nothing.
This is how you move *between* tracks
([`skip`](/api/features/queue/#skip),
[`skipToNext`](/api/features/queue/#skiptonext),
[`skipToPrevious`](/api/features/queue/#skiptoprevious)); seeking *within* the
active track (`seekTo` / `seekBy`) lives in [Playback](/guide/playback).
## Editing the queue
[`add`](/api/features/queue/#add), [`move`](/api/features/queue/#move),
[`remove`](/api/features/queue/#remove),
[`removeUpcomingTracks`](/api/features/queue/#removeupcomingtracks), and
[`load`](/api/features/queue/#load) edit the queue without rebuilding it.
Indexes refer to positions in the current queue (the same order `useQueue`
returns).
```ts
import {
add,
move,
remove,
removeUpcomingTracks,
load
} from 'react-native-audio-browser'
add(track) // append one track (also accepts a Track[])
add(track, 0) // insert before index 0 (front of the queue)
move(4, 1) // move index 4 to index 1
// On iOS and Android, toIndex past the end moves the track to the end;
// the web throws.
remove(2) // remove index 2 (also accepts number[])
removeUpcomingTracks() // drop everything after the active track
load(track) // replace the active track (or start the queue if empty)
```
The second argument to `add` is an **absolute** index, not "after the active
track". For a real **play-next** button, insert right after the active track:
```ts
import { add, getActiveTrackIndex } from 'react-native-audio-browser'
const i = getActiveTrackIndex()
add(track, i === undefined ? 0 : i + 1)
```
With shuffle on, the inserted track goes to a random place in the shuffle
order, so it may not play next.
**Removing the active track** makes the track after it active. On iOS and the
web that is the next index, wrapping to the first track, and playback carries
on.
On Android it is the next track in playback order, with shuffle and repeat
applied. If you remove the last track there, the first track becomes active,
and with repeat `'off'` playback ends.
With several indexes, Android checks them all first and throws on a repeated
one. iOS removes from the highest index down. A repeated index then also removes
the track that moved into its place, and an invalid index can throw after some
tracks are already gone. Pass each index once.
## Repeat and shuffle
[Repeat mode](/api/features/queue/#repeatmode) is one of `'off'`, `'track'`,
or `'queue'`:
| Mode | Behavior |
| --------- | -------------------------------------------------------------------------- |
| `'off'` | Pause at the end of the last track; state becomes `'ended'` (the default). |
| `'track'` | Repeat the active track forever. |
| `'queue'` | Loop the whole queue. |
```tsx
import {
setRepeatMode,
useRepeatMode,
toggleShuffle,
useShuffle
} from 'react-native-audio-browser'
function RepeatButton() {
const mode = useRepeatMode()
const next = mode === 'off' ? 'queue' : mode === 'queue' ? 'track' : 'off'
return (
setRepeatMode(next)} />
)
}
function ShuffleButton() {
const on = useShuffle()
return (
toggleShuffle()}
/>
)
}
```
[`setShuffle(true | false)`](/api/features/queue/#setshuffle) sets it directly;
[`toggleShuffle()`](/api/features/queue/#toggleshuffle) flips it. Outside
React, read the current values with
[`getRepeatMode()`](/api/features/queue/#getrepeatmode) and
[`getShuffle()`](/api/features/queue/#getshuffle), and subscribe to
[`onRepeatModeChanged`](/api/features/queue/#onrepeatmodechanged) and
[`onShuffleChanged`](/api/features/queue/#onshufflechanged).
Shuffle changes only the playback order. Indexes, `getQueue` and `useQueue`
keep list order, while `skipToNext` and `skipToPrevious` follow the shuffle
order.
## When the queue ends
With repeat `'off'`, playback pauses when the last track finishes and the
playback state becomes `'ended'` (see [Playback](/guide/playback#playback-state)).
To react — autoplay more, log a session, show a prompt — subscribe to
[`onQueueEnded`](/api/features/queue/#onqueueended):
```ts
import { onQueueEnded } from 'react-native-audio-browser'
const unsubscribe = onQueueEnded.addListener(({ track, position }) => {
// `track` is the index that was active; `position` is where it stopped.
loadMoreAndPlay()
})
```
## A complete "Up Next" screen
`useQueue` plus `useActiveTrack` is enough for a reorderable list with
tap-to-play and remove:
```tsx
import { View, Text, Button, FlatList } from 'react-native'
import {
useQueue,
useActiveTrack,
getActiveTrackIndex,
getTrackIdentity,
skip,
move,
remove
} from 'react-native-audio-browser'
function UpNext() {
const queue = useQueue()
// `useActiveTrack` re-renders the list when the active track changes.
// Compare by index: the same track can be queued twice.
// `getActiveTrackIndex()` is read fresh on each render.
const active = useActiveTrack()
const activeIndex = active ? getActiveTrackIndex() : undefined
return (
`${getTrackIdentity(track) ?? ''}:${i}`}
renderItem={({ item, index }) => (
skip(index)}
style={index === activeIndex ? { fontWeight: 'bold' } : null}
>
{item.title}
{index > 0 && (
move(index, index - 1)} />
)}
remove(index)} />
)}
/>
)
}
```
A `` can't be a child of ``, so each row is a `` with the
title and buttons as siblings. A key built from the track's `id` alone, or from
[`getTrackIdentity`](/api/utils/getTrackIdentity/) alone, collides when the same
track is queued twice, so the `keyExtractor` adds the index.
## A note on units
All position arguments are **seconds** — `seekTo`, `seekBy`, the
`initialPosition` on `skip` / `skipToNext` / `skipToPrevious`, and `setQueue`'s
`startPosition`.
## API summary
| API | Purpose |
| ------------------------------------------------------------------------ | ---------------------------------------------------------------- |
| `setQueue(tracks, startIndex?, startPosition?)` | Replace the queue (doesn't auto-play; position in **seconds**). |
| `add(track \| tracks, insertBeforeIndex?)` | Append, or insert before an index. |
| `load(track)` | Replace the active track (or start the queue if empty). |
| `move(from, to)` | Reorder; `to` past the end → end (iOS, Android; the web throws). |
| `remove(index \| indexes)` | Remove track(s); see Removing the active track above. |
| `removeUpcomingTracks()` | Drop everything after the active track. |
| `skip(index, initialPosition?)` | Jump to a track (position in **seconds**). |
| `skipToNext()` / `skipToPrevious()` | Step between tracks. |
| `useQueue()` / `getQueue()` / `getTrack(i)` | Read the queue. |
| `useActiveTrack()` / `getActiveTrack()` / `getActiveTrackIndex()` | Read the active track. |
| `onActiveTrackChanged` / `onQueueChanged` / `onQueueEnded` | Subscribe to changes. |
| `setRepeatMode(mode)` / `useRepeatMode()` / `getRepeatMode()` | `'off'` / `'track'` / `'queue'`. |
| `setShuffle(bool)` / `toggleShuffle()` / `useShuffle()` / `getShuffle()` | Shuffle order. |
| `onRepeatModeChanged` / `onShuffleChanged` | Subscribe to repeat and shuffle changes. |
---
---
url: https://audiobrowser.dev/guide/remote-controls.md
description: >-
Override what the lock-screen, notification, car, and headset buttons do with
handleRemote*, observe presses with the onRemote* events, and resume the last
session after the app is killed.
---
# Remote Controls
**Remote controls** are the playback buttons on surfaces outside your app — the
iOS lock screen and Control Center, the Android notification, CarPlay and Android
Auto, and Bluetooth/headset buttons.
By default they just work: the system play/pause/next/seek buttons drive the
player for you. This guide is for the two times you need more — **overriding**
what a button does, and **observing** when one is pressed.
There are two families:
* [`handleRemote*`](#overriding-a-control) — **override** a control's behavior.
A plain setter: `handleRemoteNext(cb)`, or `handleRemoteNext(undefined)` to
restore the default behavior. To remove a button on iOS or Android, turn off
its capability.
* [`onRemote*`](#listening-to-presses) — **listen** to presses without changing
behavior (analytics, logging). An emitter:
`onRemoteNext.addListener(cb)` returns an unsubscribe function.
Both families work on **iOS and Android**. Which buttons appear at all is
governed by [`capabilities`](/guide/configuration#capabilities)
(e.g. `jumpForward` / `jumpBackward` are off by default), and on Android
[`remoteButtonLayout`](#button-layout-android) decides where they sit.
The snippets below import from `react-native-audio-browser` unless noted.
## They work by default
Without any wiring, each control drives the player:
| Control | Default action |
| ----------------------- | ----------------------------------- |
| play / pause / stop | `play()` / `pause()` / `stop()` |
| next / previous | `skipToNext()` / `skipToPrevious()` |
| seek | `seekTo(position)` |
| jump forward / backward | seek forward / back (see below) |
So you only reach for the APIs below to *change* or *watch* that behavior.
## Button layout (Android)
Android gives you **three positions and no more**. Play/pause always holds the
centre and can't be moved, so the two named positions sit on either side of it —
they are not adjacent:
```
back │ ▶ play/pause │ forward overflow ⋯
```
Set them with [`updateOptions`](/api/features/player/#updateoptions) (or at
launch via [`setupPlayer`](/api/features/player/#setupplayer)):
```ts
updateOptions({
capabilities: { jumpBackward: true, jumpForward: true, favorite: true },
android: {
remoteButtonLayout: {
back: 'jump-backward',
forward: 'jump-forward',
overflow: ['skip-to-previous', 'skip-to-next', 'favorite']
}
}
})
```
One layout drives every Android surface — the notification, the Android Auto
Now Playing screen, and the Android 13+ system media controls.
**A layout describes the whole arrangement.** All three fields are required and
nothing is merged with the defaults, so what you write is exactly what renders —
list every button you want, not just the ones you're adding. Use `undefined` for
an empty position and `[]` for no overflow:
```ts
// Live radio: a forward skip only, nothing to the left of play/pause
remoteButtonLayout: {
back: undefined,
forward: 'skip-to-next',
overflow: []
}
```
To go back to the capability-derived defaults, omit `remoteButtonLayout`
entirely or set it to `null`. That's the only switch — there's no per-field
opt-out.
### Capabilities admit, the layout arranges
A layout can **rearrange** buttons but never **add** one. Every entry is still
gated by [`capabilities`](/guide/configuration#capabilities), so naming a
button whose capability is off does nothing at all.
This catches people out, because `jumpForward` and `jumpBackward` default to
**off**:
```ts
// ✗ Both jump buttons are silently dropped — no error, no warning.
updateOptions({
android: {
remoteButtonLayout: {
back: 'jump-backward',
forward: 'jump-forward',
overflow: []
}
}
})
// ✓ Enable the capability and the layout takes effect.
updateOptions({
capabilities: { jumpBackward: true, jumpForward: true },
android: {
remoteButtonLayout: {
back: 'jump-backward',
forward: 'jump-forward',
overflow: []
}
}
})
```
The reverse also holds: placement is cosmetic. A button you leave out of the
layout still responds to a Bluetooth remote or headset as long as its
capability is enabled.
### Overflow is priority, not coordinates
`overflow` is an ordered list, and each surface renders as many buttons as it
has room for, **taking them from the front**:
| Surface | Roughly how many |
| -------------------------------------------- | ----------------------------- |
| Collapsed notification | 3 — back, play/pause, forward |
| Expanded notification (Android 12 and below) | up to 5, play/pause included |
| Android 13+ media controls | about 5 |
| Android Auto | the head unit decides |
Two consequences worth knowing:
* A head unit with a spare slot **may promote** the first overflow entry onto
the main row. Seeing an "overflow" button beside play/pause in the car is
expected, not a bug.
* A long list gets **truncated**. Put what matters most first — a `'favorite'`
in fifth place may never be drawn on a phone.
If you want a clean three-button transport row in the car, give it fewer
buttons so there's nothing to promote.
::: tip iOS
This option is Android-only. CarPlay's Now Playing buttons are configured
separately with `ios.carPlayNowPlayingButtons` — see
[CarPlay → Now Playing Buttons](/guide/carplay#now-playing-buttons).
:::
## Overriding a control
[`handleRemote*(callback)`](/api/features/remoteControls/#handleremotenext)
**replaces** a control's default action with your own. Pass `undefined` to remove
your override (restoring the default); the callback itself does nothing but what
you write — if you still want the normal action, call it yourself.
Each control has a **single** override: calling `handleRemote*` again replaces
the previous one (unlike `onRemote*`, which supports multiple listeners).
The canonical use is gating a control — e.g. a radio product with a skip
allowance — paired with a [now-playing flash](/guide/now-playing#the-flash-transient-top-priority)
for feedback, since external surfaces have no toast:
```ts
import {
handleRemoteNext,
skipToNext,
flashNowPlaying
} from 'react-native-audio-browser'
handleRemoteNext(() => {
if (skipsRemaining() > 0) {
skipToNext() // do the default action yourself
} else {
flashNowPlaying({ artist: 'Skip limit reached' }, 3000)
}
// Note: onRemoteNext listeners still fire on both branches (see below).
})
// To remove the override and restore the default skip:
handleRemoteNext(undefined)
```
Overrides exist for `play`, `pause`, `next`, `previous`, `stop`, `seek`,
`jumpForward`, and `jumpBackward`. The ones carrying data receive a typed event:
```ts
import {
handleRemoteSeek,
handleRemoteJumpForward
} from 'react-native-audio-browser'
handleRemoteSeek(({ position }) => {
// position is in seconds
})
handleRemoteJumpForward(({ interval }) => {
// interval is in seconds
})
```
On iOS and Android the jump controls only appear when `jumpForward` /
`jumpBackward` are enabled in [`capabilities`](/guide/configuration#capabilities)
(off by default); on web capabilities are ignored and the browser's seek
forward and back actions are always handled. On iOS and Android your handler
receives the `forwardJumpInterval` / `backwardJumpInterval` option (default
15s) as `interval`; on web it receives the offset the browser sends, or 10s
when it sends none. Without a handler, the distance of the default jump depends
on the platform:
* **iOS** seeks by the interval.
* **Android** seeks by Media3's default increments (15s forward, 5s back),
whatever the interval. There the interval sets only the button's icon and the
handler's `interval`. To jump by the interval on Android, override the control
and call `seekBy(±interval)`.
* **Web** seeks by the offset the browser sends, or 10s when it sends none.
## Listening to presses
[`onRemote*`](/api/features/remoteControls/#onremotenext) subscribes to a press
**without** changing behavior — for analytics or logging. `addListener` returns a
cleanup function, and you can register multiple listeners:
```ts
import { onRemoteNext } from 'react-native-audio-browser'
const unsubscribe = onRemoteNext.addListener(() => {
logEvent('remote_next')
})
// later:
unsubscribe()
```
::: warning `onRemote*` fires even when overridden
`onRemote*` reports that the **button was pressed**, not that the default action
ran. It fires on every press — including when a `handleRemote*` override
intercepted it (and even when that override refused to act). Use it to *observe*;
use `handleRemote*` to *change behavior*.
:::
## Resuming after the app is killed
The library saves the last session natively, with nothing to configure: the
active track (with the browse path it was tapped from), its position, and the
repeat mode, shuffle and rate.
It saves on every pause, track change and setting change, and periodically
while playing, so a kill loses at most a few seconds of position. A live stream
keeps no position, so it resumes at the live edge; a track that had ended
resumes from the start.
That session plays again when a listener asks for playback while your app isn't
running:
* **Android**: a Bluetooth or headset play button, a car head unit, or the play
button on the system media controls, which keep your app's last session after
it is killed.
* **iOS**: Siri — "play «App»" or a bare "play" / "resume" (see
[Search → Voice playback](/guide/search#voice-playback-siri-google-assistant)).
Siri is the only path that resumes a saved session on iOS.
Resuming restores the settings, then rebuilds the queue by expanding the saved
track's path through your browse configuration, as if the listener had tapped it
again, and plays from the saved position.
If the path doesn't expand, the saved track plays alone. A saved track marked
[`disabled`](/guide/track) is never resumed.
Resuming waits for your JS: call `setupPlayer()` and `configureBrowser()` at the
top level of `index.js`. Resuming gives up within seconds if they haven't run
(on iOS, see
[CarPlay → AppDelegate intent handler](/guide/carplay#_4-appdelegate-intent-handler)).
On Android 12+, battery restrictions can block the background start; see
[Battery](/guide/battery).
## Voice commands ("play X")
A voice command like "play jazz on Android Auto" or a Siri "play …" is **not**
delivered as a remote-control event.
It's handled by the library's [search source](/guide/search) and play funnel:
you provide `configureBrowser({ search })`, and the library resolves the query
and starts playback for you (Android routes the system `MEDIA_PLAY_FROM_SEARCH`
intent through it). See [Search](/guide/search) for wiring voice intents.
## Payloads at a glance
| Event | Payload |
| ----------------------------------------------- | ------------------------ |
| `play` / `pause` / `stop` / `next` / `previous` | *(none)* |
| `seek` | `{ position }` — seconds |
| `jumpForward` / `jumpBackward` | `{ interval }` — seconds |
## API summary
| API | Purpose |
| ---------------------------------------------------------------------------------- | ----------------------------------------------------- |
| `handleRemotePlay/Pause/Stop/Next/Previous(cb \| undefined)` | Override a control; `undefined` restores the default. |
| `handleRemoteSeek(cb)` / `handleRemoteJumpForward/Backward(cb)` | Override, with a typed event payload. |
| `onRemotePlay/Pause/Stop/Next/Previous.addListener(cb)` | Observe a press (fires even when overridden). |
| `onRemoteSeek` / `onRemoteJumpForward` / `onRemoteJumpBackward` `.addListener(cb)` | Observe, with payload. |
Every `onRemote*` is an emitter: `.addListener(cb)` returns an unsubscribe
function. Every `handleRemote*` is a setter: pass a callback, or `undefined` to
clear it.
---
---
url: https://audiobrowser.dev/guide/browser.md
description: >-
The reference for configureBrowser: every source shape (static, callback, JSON
API), routing and path patterns, request transforms, and BrowserConfiguration
option.
---
# Browser
The **Browser** is the subsystem that turns one declarative description of your content into a navigable tree — the same tree that powers your in-app browse UI, CarPlay, and Android Auto.
You describe it once with **`configureBrowser`**; the library resolves paths, fetches children, transforms requests, and renders the native surfaces for you.
[Basic Usage](/guide/basic-usage) introduces the browse tree. This guide is the reference for *configuring* it: every source shape, every routing pattern, and every option on [`BrowserConfiguration`](/api/types/browser/#browserconfiguration).
## A complete example
Here is a full, runnable configuration — call `setupPlayer` once, then `configureBrowser` once. It has two tabs, two **static** routes, and one **callback** route. Paste it, swap in your own content, and you have a working browse tree on phone, CarPlay, and Android Auto.
```ts
import { setupPlayer, configureBrowser } from 'react-native-audio-browser'
await setupPlayer()
configureBrowser({
tabs: [
{ title: 'Browse', path: '/browse' },
{ title: 'Favorites', path: '/favorites' }
],
routes: {
// Static data declared inline:
'/browse': {
path: '/browse',
title: 'Browse',
children: [
// browsable — has a path
{ title: 'Jazz', path: '/browse/jazz' },
// playable — has a src
{ title: 'Smooth Floret FM', src: 'https://example.com/floret.mp3' }
]
},
// Resolved on demand from your own code:
'/browse/jazz': async () => {
const stations = await fetchJazzStations() // your code
return { path: '/browse/jazz', title: 'Jazz', children: stations }
},
'/favorites': {
path: '/favorites',
title: 'Favorites',
children: [
{ title: 'Smooth Floret FM', src: 'https://example.com/floret.mp3' }
]
}
}
})
```
::: tip "Your code" vs. library API
Helpers like `fetchJazzStations`, `fetchAlbum`, `getLocalFavoriteIds`, and `getDomain` throughout this guide are **your** functions, not library exports — they stand in for however your app gets its data. Only imports from `react-native-audio-browser` are library API.
:::
Calling `configureBrowser` again **replaces** the entire configuration — see [Updating the configuration](#updating-the-configuration). The rest of this guide unpacks each part.
## How a path resolves
Everything the Browser shows is the result of resolving a **path** (a string like `/browse/jazz`) to a **page** — a Track carrying its content. The flow is always the same:
```mermaid
graph LR
P["path /browse/jazz"] --> M["match a route (most specific wins)"]
M --> S["resolve its source (static · callback · HTTP)"]
S --> Page["page ResolvedTrack { path, title, sections }"]
classDef step fill:#e3f2fd,stroke:#1976d2
class P,M,S,Page step
```
A **page** is a [`ResolvedTrack`](/api/types/browser-nodes/#resolvedtrack): it requires a `path` and a `title`, and carries its content as `sections` — an array of [`Section`](/api/types/browser-nodes/#section)s, each a titled, styled group of [`Track`](/api/types/browser-nodes/#track)s:
```ts
{
path: '/home',
title: 'Home',
sections: [
{
title: 'Popular',
style: { display: 'grid', gridWrap: false },
path: '/popular',
children: [...]
},
{ title: 'All stations', children: [...] }
]
}
```
A Section is `{ title?, style?, path?, children }`. `title` renders as a header above its tracks. `style` is a declaration block whose `display` picks the children's layout: `'list'` rows (the default) or `'grid'` artwork tiles, with `gridWrap: false` keeping the grid to a single line.
`path` is the navigation target for the section's "view all" affordance.
See [Presentation](#presentation) for how each surface renders the declarations.
A flat page doesn't have to spell that out: authoring a plain `children: Track[]` — as most examples in this guide do — is sugar for one untitled section. Resolved output always carries `sections`; `children` is never populated on a resolved page.
So configuring the Browser is really three decisions, covered in turn below: **what routes exist**, **what source each route resolves from**, and **how requests are shaped** along the way.
## Source shapes
Wherever the Browser needs content — a route, the `tabs`, `search` — you supply a **source**. A route's source is one of three shapes: static data, a callback, or an HTTP endpoint.
### 1. Static data
A page object you declare inline. Best for small, fixed trees.
```ts
configureBrowser({
routes: {
'/browse': {
path: '/browse',
title: 'Browse',
children: [
// browsable — has a path
{ title: 'Jazz', path: '/browse/jazz' },
// playable — has a src
{ title: 'Smooth Floret FM', src: 'https://example.com/floret.mp3' }
]
}
}
})
```
### 2. A callback
A function `({ path, routeParams }) => ResolvedTrack` (sync or async). Resolve children from anywhere — memory, a database, your own fetch logic. Best for trees too large to declare upfront, or content that depends on runtime state.
```ts
configureBrowser({
routes: {
'/albums/{id}': async ({ routeParams }) => {
const album = await fetchAlbum(routeParams?.id) // your code
return {
path: `/albums/${album.id}`,
title: album.name,
children: album.tracks
}
}
}
})
```
Return `{ error: 'message' }` instead of a page to signal a failure the Browser should surface — see [Error handling](#error-handling).
### 3. An HTTP endpoint
A [`TransformableRequestConfig`](/api/types/browser/#transformablerequestconfig). The library issues the request **natively** (so browse works on a cold car start with your JS not yet running) and expects a page object — a `ResolvedTrack` — back.
The key convenience: with a `baseUrl` set, **any path with no explicit route is fetched over HTTP automatically** — the navigated path becomes the request path. So a fully server-driven tree may need *no* `routes` at all:
```ts
configureBrowser({
// GET https://api.example.com/browse/jazz
// (the navigated path flows through automatically)
request: { baseUrl: 'https://api.example.com' }
})
```
::: warning A static `path` does not rewrite the request path
On an HTTP route, the *navigated* path is used as the request path — a static `path` field is ignored for this. To remap (e.g. send `/favorites` to `/favorites/v2`), use a [transform](#transforms-per-request), which also receives `routeParams`.
:::
::: tip Tabs and search
`tabs` accepts the same three shapes, but its static form and its callback give a `Track[]`, not a page. `search` accepts a callback or an HTTP endpoint, with no static form. Its callback receives the search params and returns a `Track[]`:
```ts
configureBrowser({
search: async ({ query }) => searchStations(query) // your code → Track[]
})
```
Search has its own depth (voice intents, query modes) — see [Search](/guide/search).
:::
## Tabs and the initial path
`tabs` are the top-level entry points — the segmented control in your app, the tab bar on CarPlay, the root of the Android Auto tree. Each tab is a Track with a `title` and a `path` pointing at a route.
```ts
configureBrowser({
tabs: [
{ title: 'Home', path: '/home' },
{ title: 'Favorites', path: '/favorites' },
{ title: 'Browse', path: '/browse' }
]
})
```
::: warning Car surfaces show only the first few tabs
Android Auto shows the first **4** tabs. CarPlay shows as many as `CPTabBarTemplate.maximumTabCount` allows. Only those surfaces hide the extra tabs: `getTabs` and `useTabs` return every tab. A debug build warns when a static `tabs` array has more tabs than Android Auto shows.
:::
::: tip A tab's path stays a tab
Link freely to a tab's own path — a "view all" section header on one tab pointing at another tab's route, say. On CarPlay (iOS 17+) that **switches to the tab** instead of pushing a second copy of it onto the current tab's stack.
The user lands where the tab bar already shows that content, with no Back button to a page they never came from. Elsewhere — earlier iOS, Android Auto, your app UI — it navigates as usual.
:::
Like any source, `tabs` can also be a **callback** — useful when the tabs themselves depend on runtime state, such as a debug build or the current user:
```ts
configureBrowser({
tabs: () => [
{ title: 'Home', path: '/home' },
{ title: 'Favorites', path: '/favorites' },
...(__DEV__ ? [{ title: 'Debug', path: '/debug' }] : [])
]
})
```
…or an **HTTP endpoint** returning a page (`{ children: Track[] }`).
**Initial path.** The Browser opens to the first tab's `path` by default. Set `path` to start somewhere else:
```ts
configureBrowser({
// where browse opens; defaults to the first tab's path (or '/')
path: '/home',
tabs: [
/* … */
]
})
```
## Routes
`routes` maps **path patterns** to sources. When the Browser resolves a path, it finds the matching pattern and resolves that pattern's source.
### Pattern syntax
Patterns match on **exact segment count** first — `/artists` does *not* match `/artists/123`. Within that, a segment can be:
| Pattern | Matches | Captured |
| -------------- | --------------------------------------------------------- | ------------------ |
| `/favorites` | exactly `/favorites` | — |
| `/albums/{id}` | `/albums/floret`, `/albums/42` | `routeParams.id` |
| `/artists/*` | any single segment at that position (`/artists/anything`) | — |
| `/files/**` | `/files` itself, and `/files/...` at any depth below | `routeParams.tail` |
On `/files` itself, `routeParams.tail` is `undefined`.
When several patterns match, **most specific wins**: constant > `{param}` > `*` > `**`. So `/albums/new` and `/albums/{id}` can coexist — `/albums/new` takes the literal route.
```ts
configureBrowser({
routes: {
// literal — checked first
'/albums/new': newReleasesPage,
// {id} otherwise
'/albums/{id}': ({ routeParams }) => fetchAlbum(routeParams?.id),
// deep file paths
'/files/**': ({ routeParams }) => listFiles(routeParams?.tail)
}
})
```
::: warning The bare `'*'` key is the *default*, not a wildcard segment
A single-segment wildcard only works as a `*` **segment inside a longer pattern** (e.g. `/artists/*`).
The bare top-level key `'*'` is different: it's the **custom default** — the source used for any path no other route matches (and only needed if you want to override the built-in HTTP default).
```ts
routes: {
// wildcard segment — matches /artists/
'/artists/*': handleArtist,
// default for everything unmatched
'*': { baseUrl: 'https://api.example.com' }
}
```
:::
### Route parameters
A callback (or transform) receives the captured params in `routeParams`:
```ts
'/stations/{country}/{city}': async ({ routeParams }) => {
// /stations/nl/amsterdam → { country: 'nl', city: 'amsterdam' }
return fetchStations(routeParams?.country, routeParams?.city)
}
```
### Per-route overrides
A route value can be a bare source (the common case) **or** a [`RouteConfig`](/api/types/browser/#routeconfig) object that overrides request behavior for just that subtree — its `browse` source, plus its own `artwork` config. The web ignores a route's `artwork` and uses the top-level `artwork` config.
```ts
configureBrowser({
routes: {
'/premium/**': {
browse: { baseUrl: 'https://premium-api.example.com' },
artwork: { baseUrl: 'https://premium-images.cdn.example.com' }
}
}
})
```
This is how you point one branch of the tree at a different backend without touching the rest.
## Shaping requests
For HTTP sources, you rarely repeat the same `baseUrl`, headers, and query params on every route. Instead you set them once and let them **layer**. From most general to most specific:
```
request → browse → route
(all kinds) (browse only) (this route only)
```
`request` also feeds `media`, `artwork`, and `search`; `browse` narrows to browse requests; a route's own config wins last.
```ts
configureBrowser({
request: { baseUrl: 'https://api.example.com', headers: { 'x-app': 'demo' } },
browse: { query: { client: 'audio-browser', hl: 'en' } },
routes: {
// adds genre=jazz on top of the request and browse layers;
// the navigated path is the request path
'/browse/jazz': { query: { genre: 'jazz' } }
}
})
```
A path that needs nothing extra needs no route at all: an unmatched path is fetched through `request` and `browse`. An empty route object (`{}`) is not a request config: it is read as a static page with no `path` or `title`. On iOS and Android `configureBrowser` throws on it, on web it renders a blank page, and a debug build warns about it.
### RequestConfig fields
Every request layer is a [`RequestConfig`](/api/types/browser/#requestconfig) — set only the fields you need. Headers and query params merge key by key; other fields override:
| Field | Purpose |
| ---------------------- | ------------------------------------------------------------------------------------ |
| `baseUrl` / `path` | Where to send the request (note: `path` doesn't override the navigated browse path) |
| `method` | `GET` (default), `POST`, … |
| `headers` | HTTP headers (merged key by key) |
| `query` | Query parameters (merged key by key) |
| `body` / `contentType` | Request body, sent for `POST`, `PUT` and `PATCH` (and `DELETE` when set); not on web |
| `userAgent` | `User-Agent` override (a `User-Agent` in `headers` wins on iOS); ignored on web |
### Transforms: per request
When a layer needs to change *per request* (read the captured `routeParams`, switch a `GET` to a `POST`, remap the path), add a `transform` (async) or `transformSync`. It receives the merged request and returns the final one:
::: warning A transform replaces — it doesn't merge
Your return value **becomes** the request; the layer's own static fields are *not* merged back in. Always **spread the incoming `request`** (`{ ...request, … }`) — a transform that returns a bare `{ method: 'POST' }` silently drops the inherited `baseUrl`, `headers`, and `query`.
:::
```ts
configureBrowser({
routes: {
'/favorites': {
// turn the favorites browse into a POST carrying locally-stored ids
transformSync: (request) => ({
...request,
method: 'POST',
// remapping the path is valid here, in a transform
path: '/favorites/v2',
contentType: 'application/json',
body: JSON.stringify({ ids: getLocalFavoriteIds() }) // your code
})
}
}
})
```
### Resolvers: values that change rarely
When the *whole* config depends on runtime state — a domain that varies by environment, a locale, an auth host — make the layer a **resolver**: a thunk returning the config.
It runs **once per content generation** and is cached until you call [`invalidateAllContent`](#updating-the-configuration), so it's the cheap place to read values that change rarely:
```ts
configureBrowser({
// re-evaluated only when content is regenerated, not per request
request: () => ({
baseUrl: `https://${getDomain()}/api`, // your code
userAgent: resolveUserAgent() // your code
}),
browse: () => ({ query: { hl: resolveLocale() } }) // your code
})
```
::: tip Resolver vs. transform
**Resolver** (the layer *is* a function): runs once, cached — for values that change rarely. **Transform** (a `transform` field *on* the layer): runs every request — for per-request shaping. Reach for a resolver first; add a transform only when a single request genuinely differs.
:::
## Media and artwork
The same request machinery shapes the **audio stream** request (`media`) and **image** requests (`artwork`). Both layer on top of `request`, and both add a per-track `resolve` / `resolveSync` so a single track can build its own stream or image request from its metadata:
```ts
configureBrowser({
media: {
// build the stream request per track — e.g. a signed URL
resolve: async (track) => ({
path: `/stream/${track.id}`,
query: { token: await sign(track.id) }
})
},
artwork: {
baseUrl: 'https://images.example.com',
// tell the library which query params carry the requested size
imageQueryParams: { width: 'w', height: 'h' }
}
})
```
With `imageQueryParams`, CarPlay and Android Auto's requested size is injected automatically (`?w=200&h=200`) so each surface gets right-sized art. For full control, an `artwork.transform` receives that size as an [`ImageContext`](/api/types/browser/#imagecontext).
**Now-playing art** can differ from browse-row art — set `nowPlayingArtwork` for the lock screen / car now-playing surface only. Like `artwork`, it can use an `{id}` template filled from the active track's `id`:
```ts
// {id} templating (in any artwork config) is native-only:
// the web implementation does not apply it
configureBrowser({
// {id} → the active track's id
nowPlayingArtwork: { path: '/artwork/{id}' }
})
```
See [Now Playing](/guide/now-playing) for the metadata side of the now-playing surface.
## Playback behavior
Two options control what happens when a playable Track is tapped.
**`singleTrack`** — by default, tapping a track queues **its section** and starts there, so next/previous walk the list the user tapped in.
The scope is the page's declared structure: the tapped [Section](#how-a-path-resolves)'s `children`, identical on every surface (a page authored with plain `children` is one untitled section). Rendering may truncate what a section *shows* — a CarPlay single-line grid fits only so many tiles — but never what *plays*.
A page aggregating several sections never leaks next/previous across them. Set `singleTrack: true` to play only the tapped track. If the track has meanwhile disappeared from its section (a stale resume, say), the library plays it as a single track rather than guessing a queue from the changed list.
Section scoping knows *where* the tap happened, not just on what. Each playable row's path carries the track's identity (`id`, falling back to `src`) and the row's position on the page.
So the same track can safely appear in several places on one page: a tap queues the section it happened in, and when a playlist holds the same track twice, next/previous continue from the tapped copy.
The position is only a tie-breaker. If the page has changed by the time the queue is expanded (a stale resume, say), the first row matching the identity wins instead — a stale position can pick a different copy of the tapped track, never a different track.
Tapping a row that's already in the current queue from the same page skips in place rather than requeueing the section.
**`handleTrackLoad`** — intercept loading entirely. When set, tapping a track calls *your* handler **instead of** the library auto-playing, and native waits for your promise to resolve before continuing. The two branches differ:
```ts
import { configureBrowser, setQueue, play } from 'react-native-audio-browser'
configureBrowser({
handleTrackLoad: async ({ track, queue, startIndex, startPosition }) => {
if (isVideo(track)) {
// your surface — return without touching the player; audio stays put
openVideoPlayer(track)
return
}
// audio: drive playback yourself — the library won't auto-play
setQueue(queue, startIndex, startPosition)
play()
}
})
```
In the video branch, returning without calling the player tells the library the tap is handled and audio stays as it is. In the audio branch, call [`setQueue` and `play`](/guide/basic-usage) yourself. Both return `void`, so there is nothing to await on them.
Native **awaits the promise your handler returns**. Anything you `await` inside, such as an auth check or a fetch, delays the tap being treated as handled. Keep slow work out of the handler, or start it without awaiting it.
## Reading and driving browse state
The Browser exposes its current state through getters, React hooks, and event emitters — so your in-app UI can mirror exactly what the car shows.
```tsx
import {
useTabs,
usePath,
useContent,
navigate
} from 'react-native-audio-browser'
function BrowseScreen() {
const tabs = useTabs() // Track[] | undefined
const path = usePath() // current path
const page = useContent() // resolved page (page.sections to render)
return (
<>
{tabs?.map((tab) => (
navigate(tab.path!)} />
))}
{page?.sections?.map((section, i) => (
{section.title && }
{section.children.map((track) => (
navigate(track)}
/>
))}
))}
>
)
}
```
`navigate` takes either a **path** (browse into it) or a **Track** (play it). The getters (`getPath`, `getContent`, `getTabs`) and emitters (`onPathChanged`, `onContentChanged`, `onTabsChanged`) cover non-React call sites. To inspect the config you set, `getBrowserConfiguration()` returns it (or `undefined` before `configureBrowser` runs).
## Updating the configuration
The tree isn't static — content changes, languages switch, environments move. Three tools, smallest blast radius first:
| Need | Use |
| -------------------------------------------------- | ------------------------------------ |
| One path's children changed | `notifyContentChanged('/favorites')` |
| Everything is stale (locale, domain, auth changed) | `invalidateAllContent()` |
| The config *shape* itself changed | `configureBrowser(newConfig)` |
`notifyContentChanged(path)` refreshes a single path in place — external controllers re-fetch just that page. `invalidateAllContent()` clears every cache and re-resolves all visible surfaces (and re-runs your [resolvers](#resolvers-values-that-change-rarely)) — this is what you call after a language or domain switch.
`configureBrowser` replaces everything wholesale and re-runs initial navigation: the in-app browser opens `path` (or the first tab) again. On web it opens the first tab only when `tabs` is an array, and `/` otherwise. CarPlay and Android Auto keep their place; if the tabs changed, CarPlay rebuilds its tab bar once the user is back at the root.
```ts
// language changed → resolvers read the new locale on the next resolve
onLocaleChange(() => invalidateAllContent()) // onLocaleChange is your code
```
## Error handling
When a source fails — network down, a callback throws, an HTTP non-2xx, an empty container — the Browser raises a typed `NavigationError`. On CarPlay / Android Auto it shows a built-in message; in your app you read it via `useNavigationError`.
Customize the copy with `formatNavigationError` — branch on the `code` and the `path`, and fall back to the library's default for the rest:
```ts
configureBrowser({
formatNavigationError: ({ error, defaultFormatted, path }) => {
if (error.code === 'empty-content' && path.startsWith('/favorites')) {
return {
title: 'No favorites yet',
message: 'Tap the heart on a station to add it.'
}
}
if (error.code === 'network-error') {
return {
title: 'No connection',
message: 'Check your connection and try again.'
}
}
return defaultFormatted
}
})
```
For the `code` values, see [Navigation errors](/guide/errors#navigation-errors). Your formatter drives both the car dialogs and the [`useFormattedNavigationError`](/api/features/errors/#useformattednavigationerror) hook in your app.
## Presentation
Presentation lives in `style` blocks, separate from content, plus a few Track fields and config options. Each surface applies the style properties it supports and ignores the rest — an unsupported property is a no-op, never an error.
| Field | On | Effect | Platform |
| ------------------------------------------------ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |
| `title` | a section | header above its tracks | all |
| `style: { display: 'grid' }` | a section | wrapping artwork-tile grid | all\* |
| `style: { display: 'grid', gridWrap: false }` | a section | a single line of artwork tiles | all\* |
| `path` | a section | "view all" target: a tappable row on a CarPlay grid (none on a list); an appended `viewMoreTitle` row on Android Auto | all |
| `style` (same block) | a page | declaration for the whole page — a section overrides it for its own children | all |
| `style: { display: 'grid' }` | a browsable track | the layout of the page it opens — Android Auto reads it from the parent item | Android Auto / AAOS |
| `style: { artworkRendering: 'stencil' }` | a track / section / page | tint monochrome artwork to the surface appearance | CarPlay |
| `style: { imageShape: 'circular' }` | a track / section / page | crop `'image'` and `'condensed'` tile artwork circular (people) | CarPlay (iOS 26+) |
| `style: { accessorySymbol: 'lock.fill' }` | a track / section / page | SF Symbol accessory on rows and on `'image'` / `'condensed'` tiles | CarPlay |
| `style: { gridTile: 'card' }` | a section / page | the grid's tile kind: `'plain'` (default), `'image'`, `'card'`, or `'condensed'` | CarPlay (iOS 26+) |
| `style: { cardTint: '#1e3a8a' }` (+ `cardImage`) | a track / section / page | card color and image mode (`'background'` fills the card full-height) | CarPlay (iOS 26+) |
| `disabled: true` | a track | unavailable: taps, voice selection, queue expansion and resume refuse it, but a `setQueue` list is not filtered and plays it when reached; grayed where drawable, hidden elsewhere | all |
| `artwork: 'sf:heart.fill'` | any item | SF Symbol icon (supports `?bg=…&fg=…`) | iOS |
| `live: true` | a track | live indicator | iOS |
| `carPlaySiriListButton: 'top' \| 'bottom'` | a page | place the Siri cell on the page | iOS |
| `albumPath` or `resolveAlbumPath` | track or config | make the now-playing album line tappable | CarPlay |
::: info Caveats from the table
* **The album line needs `album`.** CarPlay draws the tappable line from the album metadata, so a track with no `album` has no line to tap.
* **\*Layouts render each platform's nearest supported form.** On CarPlay, a single-line grid (`gridWrap: false`) shows the tiles that fit on one line (about seven on a wide screen, or two condensed cells). A wrapping grid takes as many lines as it needs on iOS 26+, and is a list before that.
* **Android Auto's grid always wraps**, so it shows more, never less. No car surface scrolls horizontally. An app UI typically renders `gridWrap: false` as a horizontal scroller.
* **Truncation is visual only.** Tapping a tile queues the whole section (see [Playback behavior](#playback-behavior)).
* **Item properties are inherited.** `artworkRendering`, `imageShape` and `accessorySymbol` resolve as `track ?? section ?? page`, per property, so an item can override a section-wide value. `accessorySymbol: 'none'` removes an inherited symbol from one item.
* **The platform places the accessory.** It is trailing on list rows and condensed tiles, and leads the title on image tiles.
* **On an iOS 26 grid, `gridTile` decides what each tile draws.** `'plain'` has a subtitle but no shape and no accessory. `'image'` has a shape and an accessory but no subtitle. `'condensed'` has all three beside a small image. `'card'` has a subtitle, a tint and an image mode.
* **`display` is never inherited.** It describes the children of whatever it is set on. On a browsable track it declares the layout of the page the track opens: Android Auto needs it there, or that page renders as a list.
* **`gridWrap` is inert unless `display` is `'grid'`.**
* **AAOS honors only the parent item's `display`.** AOSP-based Automotive units render a page that mixes grid and list sections in one layout. See [Android Auto → Browse display](/guide/android-auto#browse-display).
:::
::: tip Inert declarations are logged in debug builds
Some combinations can never render. They are inert, not errors, so nothing breaks:
* `gridWrap` or `gridTile` outside a grid
* `cardTint` with no card treatment in scope
* `imageShape` anywhere but an image or condensed grid
* `accessorySymbol` on a plain or card grid
* `display` on a track that renders playable
In a **debug build**, each one is logged once per page resolution (`Timber` on Android, `os.log` on iOS) naming the section, the effective style, and the fix:
```
Inert style declaration on page '/home': `style.gridWrap` on section 'Featured'
never renders — `gridWrap` renders only in a grid, but its effective style is
display 'list'. Declare `display: 'grid'` on the section or the page, or drop
`gridWrap`.
```
A property a *surface* can't draw is never reported — that's the aspirational rule working, not a mistake. Release builds skip the check entirely, so a page you only ever serve to a release build reports nothing; browse it from a debug build to see the findings.
:::
```ts
// A grid page. Android Auto also needs display: 'grid' on the item
// that opens this page — see the Android Auto guide:
{
path: '/genres',
title: 'Genres',
style: { display: 'grid' },
children: [...]
}
{
path: '/home',
title: 'Home',
sections: [
{
title: 'Popular',
style: { display: 'grid', gridWrap: false },
path: '/popular',
children: [...]
},
// Round tiles for people: the image tile is the one with a shape.
{
title: 'Artists',
style: { display: 'grid', gridTile: 'image', imageShape: 'circular' },
children: [...]
},
{ title: 'All stations', children: [...] }
]
}
{
title: 'Favorites',
path: '/favorites',
artwork: 'sf:heart.fill?bg=#FF0090&fg=#fff'
}
```
::: tip See every style rendered
The example app's **Style Lab** tab draws each `style` declaration on CarPlay: one page per `gridTile` value, plus pages for section headers and for inheritance from page to section to track.
Every shelf is titled with the block it renders, so what you see on screen names what to copy.
The pages are plain route data in [`style-lab.ts`](https://github.com/radio-garden/react-native-audio-browser/blob/next/apps/example-native/src/utils/style-lab.ts), with a comment on each example saying what it shows.
:::
Three config-level platform options round it out:
* `carPlayLoadingTitle`: a localized "Loading…" on older CarPlay.
* `androidControllerOfflineError`: shows an offline error in Android Auto and other external controllers when the network is lost. It defaults to `true`.
* [`viewMoreTitle`](/api/types/browser/#viewmoretitle): titles the "view more" row Android Auto appends to a section with a `path`. It is read again on `invalidateAllContent()`.
The CarPlay now-playing album line is tappable when the active track has an `albumPath`. For tracks without one, a `resolveAlbumPath` callback maps the track to a browse path. In both cases the track needs an `album`. See [CarPlay](/guide/carplay) and [Android Auto](/guide/android-auto) for the platform setup these build on.
## Where to go next
`configureBrowser` is also where you wire up the adjacent subsystems, each with its own guide:
* **[Search](/guide/search)** — the `search` source: voice and text queries → tracks.
* **[Favorites](/guide/favorites)** — heart buttons and a synced favorites collection.
* **[Now Playing](/guide/now-playing)** — lock-screen / car metadata for the active track.
* **[Gate](/guide/gate)** — gating playback behind a paywall or region check.
For every type referenced here — [`BrowserConfiguration`](/api/types/browser/#browserconfiguration), [`Track`](/api/types/browser-nodes/#track), [`RequestConfig`](/api/types/browser/#requestconfig), [`NavigationError`](/api/features/errors/#navigationerror) — see the [API reference](/api/).
---
---
url: https://audiobrowser.dev/guide/favorites.md
description: >-
Let listeners heart the active track from the Android notification, Android
Auto, CarPlay, and Siri, and surface a Favorites tab and voice command.
---
# Favorites
**Favorites** let a listener mark the active track with a heart: in the Android notification and system media controls, Android Auto, the CarPlay now-playing screen, and through Siri. They also let you surface a "Favorites" tab and a "play my favorites" voice command.
The library tracks favorite *state* (which track is favorited, and keeping the heart in sync everywhere); **your app owns the collection** (where favorites are stored and how they persist).
## Enabling favorites
Favoriting is off until you enable the `favorite` capability in `setupPlayer` (or `updateOptions`):
```ts
import { setupPlayer } from 'react-native-audio-browser'
await setupPlayer({
capabilities: { favorite: true }
})
```
The identifiers you pass to [`setFavorites`](#hydrating-favorite-state) are compared against each track's **identity**: its `id` when set, falling back to its `src` ([`getTrackIdentity`](/api/utils/getTrackIdentity/) computes it). Store the same stable identifier you put in `Track.id` — or, for tracks without ids, the full `src`:
```ts
import { setFavorites } from 'react-native-audio-browser'
// track = { id: 'abc123', src: 'https://stream.example.com/jazz.mp3' }
setFavorites(['abc123']) // matches by id
// id-less track = { src: 'https://stream.example.com/jazz.mp3' }
setFavorites(['https://stream.example.com/jazz.mp3']) // matches by src
```
## Hydrating favorite state
The library keeps a native cache of which tracks are favorited. It paints hearts on Android Auto browse rows and the now-playing heart without a round-trip to JS, and **without your content API having to know which tracks are favorites**.
Declare your favorites once with `setFavorites`; the library stamps `favorited` on any track whose [identity](#enabling-favorites) matches, wherever that track appears. Your content endpoints stay favorites-agnostic — they return the same tracks for everyone, and favorite state lives entirely in your app/user storage.
```ts
import { setFavorites } from 'react-native-audio-browser'
// string[] of track identities: ids, or src URLs for id-less tracks
const favorites = await loadFavoritesFromStorage()
setFavorites(favorites)
```
You only need `setFavorites` for the initial hydrate. After that, taps on the system heart and calls to [`setActiveTrackFavorited`](#favoriting-from-your-own-ui) update the cache for you.
Your API can also return `favorited: true` on a track directly. A caller-set flag always wins over hydration for display — the library never overwrites it — but it does **not** fill the favorites cache. It only affects the response it arrived in, so other appearances of the same track stay unhearted.
Treat `setFavorites` as the source of truth, and server-supplied `favorited` as a per-response display override.
## Favoriting from system controls
Where the heart shows up depends on the platform:
* **Android:** once the capability is on, the heart sits in the overflow of the notification, Android Auto and the system media controls. You need no layout for it. A [`remoteButtonLayout`](/guide/remote-controls#button-layout-android) places it, and a layout that leaves out `'favorite'` drops it.
* **iOS:** the only heart is a button on the CarPlay now-playing screen, and you opt into it. Control Center and the lock screen show none.
```ts
import { setupPlayer } from 'react-native-audio-browser'
await setupPlayer({
capabilities: { favorite: true },
ios: { carPlayNowPlayingButtons: ['favorite'] }
})
```
On iOS, Siri can also favorite or unfavorite the playing track ("add this to my favorites", "I like this") once Siri is wired up as in [CarPlay → Siri Voice Search](/guide/carplay#siri-voice-search), with `INAddMediaIntent` and `INUpdateMediaAffinityIntent` also listed in `INIntentsSupported`. Favorites need no `search` source.
Every favorite change, from any source, updates the library's cache and the hearts, then emits `onFavoriteChanged`: a system heart tap, a Siri request, and your own calls to [`setActiveTrackFavorited`](#favoriting-from-your-own-ui) alike. Persist the change to your storage or backend here, and only here:
```ts
import { onFavoriteChanged } from 'react-native-audio-browser'
const unsubscribe = onFavoriteChanged.addListener(({ track, favorited }) => {
if (favorited) addToFavorites(track)
else removeFromFavorites(track)
})
```
The native side has already updated the now-playing heart by the time this fires, so your handler persists the change, then refreshes the `/favorites` content (see [Keep it in sync](#keep-it-in-sync)).
## Favoriting from your own UI
To drive favoriting from an in-app button (rather than a system control), set or toggle the active track's state directly. These update the same cache and system hearts:
```ts
import {
setActiveTrackFavorited,
toggleActiveTrackFavorited
} from 'react-native-audio-browser'
setActiveTrackFavorited(true)
toggleActiveTrackFavorited()
```
Both emit `onFavoriteChanged` like a system heart tap does, so the listener above persists the change. Don't persist it again in your button handler.
## Surfacing favorites
How you surface favorites in your [browse tree](/guide/basic-usage) is up to you — a top-level tab, a nested entry, or a group within a larger list. Whatever the placement, point its route at the listener's favorited tracks:
```ts
import { configureBrowser } from 'react-native-audio-browser'
configureBrowser({
tabs: [
{ title: 'Browse', path: '/browse' },
{ title: 'Favorites', path: '/favorites' }
],
routes: {
'/favorites': async () => ({
path: '/favorites',
title: 'Favorites',
// your stored favorites, as a Track[]
children: await loadFavoriteTracks()
})
}
})
```
Resolve it however your collection lives — from local storage, or from your API (with an HTTP route that posts your stored identifiers). It renders natively on CarPlay and Android Auto like any other browse content.
### Keep it in sync
The library caches each path's content, so `/favorites` keeps showing its old content until you tell it to re-fetch. **Whenever the favorites collection changes**, re-fetch it.
When the change came from outside the player, such as a sync from another device or an edit on your server, also refresh the hearts:
```ts
import { setFavorites, notifyContentChanged } from 'react-native-audio-browser'
// only for changes from outside the player: refresh the hearts
setFavorites(updatedIds)
// always: re-fetch the /favorites content
notifyContentChanged('/favorites')
```
These hit two different caches. `setFavorites` updates the `favorited` flag wherever a track appears. A heart tap, a Siri request or `setActiveTrackFavorited` already updates it, so for those the call is redundant, though harmless.
[`notifyContentChanged(path)`](/api/features/browser/#notifycontentchanged) re-runs the route handler for that one path and refreshes any surface currently showing it. Use [`invalidateAllContent()`](/api/features/browser/#invalidateallcontent) instead only when *everything* should re-fetch, such as on a locale switch or sign-out.
You can drive both calls from one place that observes your favorites list, rather than from each source of change.
## Searching within favorites
Voice intents can target the favorites collection — both "play my favorites" and a scoped search like "play my jazz". These arrive at your `search` source with `reference: 'my'`. See [Search → Playing the user's own collection](/guide/search#playing-the-users-own-collection) for how to resolve them against a local or server collection.
## API summary
| API | Purpose |
| ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `capabilities: { favorite: true }` | Enable favoriting and the system hearts. |
| `setFavorites(ids)` | Hydrate the favorites cache; ids match each track's identity (`id`, falling back to `src`). |
| `track.favorited` | Per-track display flag; a caller-set value wins over hydration but does not fill the cache. |
| `setActiveTrackFavorited(bool)` / `toggleActiveTrackFavorited()` | Favorite the active track from your own UI. |
| `onFavoriteChanged` | Fires on every favorite change (system heart, Siri, your own calls); persist the change here. |
| `notifyContentChanged('/favorites')` | Re-fetch the `/favorites` content after the collection changes. |
| `'favorite'` in `android.remoteButtonLayout` | Places the Android heart. Without a layout it sits in the overflow already. A layout replaces the defaults wholesale, so list the other buttons you still want. |
| `ios.carPlayNowPlayingButtons: ['favorite']` | The heart on the CarPlay now-playing screen, the only one on iOS. |
| `search` source with `reference: 'my'` | Resolve "play my favorites" / favorites search. |
---
---
url: https://audiobrowser.dev/guide/gate.md
description: >-
Block premium, login-only, or region-locked content on CarPlay and Android
Auto with a short message — without touching your in-app UI or interrupting
playback.
---
# Gate
A **Gate** replaces the browse content on **CarPlay**, **Android Auto** and **Android Automotive** with a short message that you hand the library. It can also turn away voice searches.
Use it when part of your catalog is premium, login-only or region-locked, and you want to block it in the car without building a separate UI there.
One rule worth keeping in mind: **a Gate blocks *finding*, never *hearing*.** Whatever is already playing keeps going, a voice "resume" is never gated, and the queue is left alone.
A voice request to play something new is a search. The Gate refuses it unless your resolver lets search through (see [Gating some requests, not others](#gating-some-requests-not-others)).
Two things it never touches:
* **Your own in-app browse UI.** The Gate only covers content the *library* serves; the screens you draw in your app are yours to gate with your own paywall.
* **Playback.** It lives on the find/resolve path, so audio is never interrupted.
It follows that the Gate is **iOS and Android only**. On web `setGate` and `clearGate` are no-ops and `onGate` never fires: there's no car surface to cover.
In-app browse UI is not the Gate's job on any platform. Calling the Gate functions from shared code is safe, and on web does nothing.
::: warning Voice search isn't only a "car" thing
A Siri or Google Assistant request ("Hey Siri, play jazz on App") can come from the phone or lock screen, not just the car. It still goes through the Gate.
That's why the common setup below **gates browsing but lets search through**: voice-play keeps working everywhere, while the car's browse tabs stay walled off.
:::
## Setting a gate
```ts
import { setGate, clearGate } from 'react-native-audio-browser'
setGate({ title: 'Premium', message: 'Subscribe to browse in the car.' })
// …later, when the user is entitled:
clearGate()
```
[`setGate`](/api/features/gate/#setgate) raises the gate (or updates it in place); [`clearGate`](/api/features/gate/#cleargate) drops it and the real content returns (on CarPlay, on the first tab; see the warning below).
Set it before the car connects and it'll be there the moment it does. A gate is global and singular — calling `setGate` again replaces the current one.
A Gate is **independent** of `setupPlayer` and `configureBrowser` — call `setGate` any time after import. The usual lifecycle is: set it once at startup, then `clearGate` (or re-`setGate`) whenever the user's entitlement changes (purchase, login, logout).
A gate is just a title and an optional message. How it renders depends on the surface:
* **CarPlay**: the tab bar stays, and each gated tab, or gated page you navigate to, shows a centered message page in place of its list (newlines in the message collapse to spaces). The Now Playing screen keeps its transport controls but hides the custom buttons from `ios.carPlayNowPlayingButtons`.
* **Android Auto and Android Automotive**: the tabs stay visible, and each gated tab's content becomes one non-playable list tile. The tile shows the **title** as its main line and the **message** as the subtitle (newlines collapse to spaces). Keep both short: it's a tile, not a full page.
There's no action button: Android Auto can't show one, and a car surface can't run a purchase flow anyway (see [Reacting to gate hits](#reacting-to-gate-hits) for the deferred-upsell pattern).
::: warning Changing the gate resets CarPlay navigation
While CarPlay is connected, every `setGate`, and every `clearGate` that drops a gate that was up, pops any drilled-in pages back to the tab root. This includes a first `setGate` on logout and a `clearGate` after a purchase. A `clearGate` with no gate up does nothing.
A `clearGate` also rebuilds the tab bar, so CarPlay returns to the first tab; `setGate` keeps the selected tab. A gate set before the car connects does not affect navigation.
:::
## Gating some requests, not others
Pass a [**resolver**](/api/features/gate/#gateresolver) as the second argument. The library calls it for every browse navigation and every search, and your return value decides what happens:
* return **`false`** — let the request through
* return **`true`** — gate it with the default message (the first `setGate` argument)
* return a [**gate object**](/api/features/gate/#gate) `{ title, message? }` — gate it with a different message, just for this one
The [request](/api/features/gate/#gaterequest) tells you what's being asked: `request.kind` is `'browse'` or `'search'`. A browse request carries a `request.path`; a search request carries `request.params` (the parsed query — see the [Search](/guide/search) guide).
The common case — **gate browsing, but leave search open** — so users can still play by voice:
```ts
setGate(
{ title: 'Premium', message: 'Subscribe to browse in the car.' },
(request) => request.kind === 'browse'
)
```
::: warning The resolver is synchronous
A resolver returns `Gate | boolean` — never a Promise — so you can't `await` an auth check inside it. Rather than check entitlement in the resolver, drive the gate from a single place: gate while locked, `clearGate` once entitled.
```ts
const gateBrowsing = () =>
setGate(
{ title: 'Premium', message: 'Subscribe to browse in the car.' },
(request) => request.kind === 'browse' // gate browse, allow search
)
if (!isEntitled()) gateBrowsing() // your code, at startup
// entitlement changed (purchase / login / logout):
function onEntitlementChange(entitled: boolean) {
entitled ? clearGate() : gateBrowsing() // refresh the car surfaces
}
```
:::
Because the resolver sees the request, you can also gate by path — block one premium branch while the rest stays open — or show a different message per request:
```ts
setGate({ title: 'Premium', message: 'Subscribe to unlock.' }, (request) => {
if (request.kind === 'search') return false // search allowed
if (request.path.startsWith('/premium')) return true // gate this branch
return false // everything else
})
```
A search request carries `request.params` — the parsed query (`query`, `genre`, `artist`, … — see [Search](/guide/search)) — so you can gate only premium queries:
```ts
setGate({ title: 'Premium', message: 'Subscribe to unlock.' }, (request) => {
if (request.kind === 'search') {
return request.params.genre === 'premium' // gate premium genres
}
return request.path.startsWith('/premium')
})
```
You can also pass **only** a resolver, with no default message. Return a gate object for full control, or `true` to fall back to the generic built-in chrome.
That fallback is a generic built-in title with no body, so on CarPlay its message area is blank. Pass a default gate or return a gate object if you want body copy.
```ts
setGate((request) => request.kind === 'browse')
```
If the resolver throws, the gate **fails closed** — the library gates the request rather than leak content. A deliberate `return false` is the only thing that lets a request through.
## Reacting to gate hits
You can't complete a purchase on CarPlay or Android Auto — so the pattern is to **record** that a user bumped into the gate and surface the upsell next time your phone app opens. Subscribe to [`onGate`](/api/features/gate/#ongate):
```ts
import { onGate } from 'react-native-audio-browser'
// addListener returns an unsubscribe function — keep it and call it to
// clean up.
const unsubscribe = onGate.addListener((event) => {
// event.reason ('browse' | 'search') is the same axis as the resolver's
// request.kind. The event carries only the reason, not the path/params.
recordGateHit() // your own persisted flag
})
```
In a component, wire it through `useEffect` so it unsubscribes on unmount:
```tsx
useEffect(() => onGate.addListener((event) => recordGateHit()), [])
```
`onGate` fires **once per gated serve**, whether the gate is static or resolver-driven. There's no de-duplication, so poking around a gated car UI fires several events — debounce on your side (once per session, per day, whatever fits) if you don't want them all.
Then, on your next app launch, read the flag and show the upsell:
```ts
if (consumeGateHit()) showPremiumUpsell() // your code: read + clear flag
```
---
---
url: https://audiobrowser.dev/guide/search.md
description: >-
Configure the search source that answers both your in-app search UI and the
voice search on Siri, CarPlay, and Android Auto.
---
# Search
**Search** is the query subsystem: it turns a voice command ("play jazz") or a text query into a list of playable tracks. It is distinct from **Browse** (navigating the content tree) — search takes structured query parameters and returns results.
Search powers both your in-app search UI and the voice search on external surfaces (Siri / CarPlay, Android Auto).
## Configuring search
Set `search` on your `BrowserConfiguration`. It takes one of two shapes:
**A callback** — resolve results yourself and return a `Track[]`. The simplest possible search just filters a list you already have in memory:
```ts
import { configureBrowser } from 'react-native-audio-browser'
configureBrowser({
// …the rest of your config (tabs, browse, request, …)
search: async ({ query }) => {
const q = query.toLowerCase()
return allTracks.filter((track) => track.title?.toLowerCase().includes(q))
}
})
```
The callback can return `Track[]` from anywhere — an in-memory filter as above, a local database, or your own API:
```ts
configureBrowser({
search: async (params) => {
// db / toTrack are yours
const rows = await db.findStations(params.query)
return rows.map(toTrack)
}
})
```
**An HTTP endpoint** — a `TransformableRequestConfig`. The library issues the request natively and appends the query parameters for you.
The endpoint must return a **bare `Track[]`**, a JSON array of results, not the page object a browse endpoint returns. iOS and Android decode only the array. On Android a page object gives no results, and on iOS the search rejects. The web accepts either shape. See [`SearchSource`](/api/types/browser/#searchsource).
```ts
configureBrowser({
search: {
baseUrl: 'https://api.example.com/search',
// "play jazz" → GET .../search with q=jazz, genre=jazz and limit=20
// (q always; genre because the intent carried one; no mode here
// because "play jazz" carries none; limit added by transformSync)
transformSync(request) {
return { ...request, query: { ...request.query, limit: '20' } }
}
}
})
```
With the HTTP form the library adds to `request.query`: `q` (always, even when empty), `mode`, `reference` (only when it is `'my'`, see below), and the filter fields, each only when the intent carried it. The callback's `query` is sent as `q`.
## Searching from your own UI
The same source powers your in-app search box. [`search(query)`](/api/features/browser/#search) runs it and resolves to a `Track[]` — it only *returns* results, it never queues or plays anything.
[`hasSearch()`](/api/features/browser/#hassearch) tells you (synchronously) whether a search source is configured at all, so you can hide the search UI when it isn't. Check it before calling [`search()`](/api/features/browser/#search): with no source configured, Android and web resolve `[]` but iOS rejects. With a source configured, `[]` means it found nothing:
```tsx
import { search, hasSearch, navigate } from 'react-native-audio-browser'
import type { Track } from 'react-native-audio-browser'
function SearchScreen() {
const [results, setResults] = useState([])
if (!hasSearch()) return null // no search source configured
return (
<>
setResults(await search(text))} />
navigate(track)} // load & play via the library
/>
>
)
}
```
Four things to know about the in-app call:
* **Your resolver sees a plain query.** An in-app `search('jazz')` arrives as `{ query: 'jazz', reference: 'unknown' }` — no `mode`, no filter fields. Only the voice assistants extract those. (On the HTTP form, only `q` is appended.) A resolver written against *the fields that are present* handles both callers.
* **You get the flat list, untouched.** The [browsable-first-result drill-in](#voice-playback-siri-google-assistant) is voice-only — in-app results are handed to you as returned, and the user picks. A result with neither a `path` nor a `src` can't be rendered, so don't return one.
* **Route taps through `navigate(track)`** rather than `setQueue` + `play` — that gives a tapped result the library's load path ([`handleTrackLoad`](#mixed-audio-video), [Gate](/guide/gate) checks, favorite hearts) just like a tap on a browse row.
* **A failed search rejects; catch it** to tell a failure from no results. On web a failed HTTP search's error carries a `code`: `'http-error'` or `'network-error'`; a callback's rejection reaches you unchanged. On Android an HTTP source never rejects: it resolves `[]` on any failure (status, network, decoding), so there a failure looks like no results. See [`search`](/api/features/browser/#search).
## SearchParams
Both forms receive the same structured `SearchParams`:
| Field | Type | Meaning |
| ----------- | ------------------- | -------------------------------------------------------------------------------------- |
| `query` | `string` | The raw query (always present, may be `""`). |
| `mode` | `SearchMode?` | The **container vertical** — what *kind* of result. Absent for an unstructured search. |
| `genre` | `string?` | Genre **filter**. |
| `artist` | `string?` | Artist **filter**. |
| `album` | `string?` | Album **filter**. |
| `title` | `string?` | Track-title filter (song intents). |
| `playlist` | `string?` | Playlist-name filter. |
| `reference` | `'my' \| 'unknown'` | Whether the user asked for *their own* collection. |
`query` and `reference` are **always present** (`reference` defaults to `'unknown'`); the short literals in the tables below omit them for brevity, but a real `SearchParams` always carries both.
## Search modes are *verticals*, not filters
`mode` answers **"what kind of thing did the user ask for?"** — a station, a podcast, a song. It is orthogonal to the filter fields, which say *which* item:
```ts
// "play a jazz podcast"
{ mode: 'podcast', genre: 'jazz', query: 'jazz' }
// ^ vertical ^ filter
```
The values:
| Mode | Asked for |
| ------------------------------------------------------- | ------------------------------------------------------------------- |
| `any` | Anything sensible — smart shuffle / "play something" (empty query). |
| `station` | A live radio station / channel. |
| `podcast` | A podcast (show, episode, or station). |
| `audiobook` | An audiobook. |
| `news` | News content. |
| `music` | The music vertical (as opposed to talk/podcasts). |
| `song` | An individual track. |
| `playlist` | A named playlist / mix. |
| `music-video` / `movie` / `tv-show` / `tv-show-episode` | Video kinds (see [Mixed audio/video](#mixed-audio-video)). |
::: tip There is no `genre`/`artist`/`album` mode
Those are **filters**, not result shapes — read them from `params.genre` / `params.artist` / `params.album` directly. A genre search arrives as `{ genre: 'jazz' }` with `mode` left unset.
:::
`mode` is **advisory** — use it to route to the right index, or ignore it and full-text search `query`.
## Cross-platform differences
The two voice platforms feed the **same** `SearchParams`; they just differ in how many fields they fill:
* **iOS (SiriKit)** supplies the richer set: every `mode` except `any`, and the `reference` axis.
* **Android (`onPlayFromSearch`)** supplies the subset it can express: `query`, the modes `any` (for "play music" with no query), `song` and `playlist`, the genre, artist, album, title and playlist filters, and always `reference: 'unknown'`.
Write your resolver against the *fields that are present* (`if (params.genre) …`), not against the platform. A field that's empty on one platform simply means "the assistant didn't provide it."
## Voice playback (Siri & Google Assistant)
A spoken command — "play jazz on «App»" — funnels to the **same `search` source** on both platforms, then the result is queued and played. Any active **[Gate](/guide/gate)** sees the search first, so voice can't slip past a paywall or region block unless your gate lets it through.
::: tip A browsable first result is drilled into
The library inspects the **first** voice result. If it is browsable-only — a `path` with no `src` — the library resolves that page and queues *its* playable children. So "play jazz" plays the first station *inside* the jazz page, not the page itself.
Disabled results are skipped, so a disabled first result never counts. If the first result is already playable (has a `src`), or the drill-in finds nothing playable, the playable results (those with a `src` that are not `disabled`) are queued in order.
This applies on both platforms, and only to voice playback — an in-app search UI renders your results and lets the user pick.
:::
For ordinary queries ("play jazz", "play «station name»") the two behave identically — same resolver, same queue, same playback. The entry point and a few conveniences differ:
| | iOS (Siri) | Android (Google Assistant) |
| ----------------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| Delivered as | `INPlayMediaIntent` | `MEDIA_PLAY_FROM_SEARCH` intent |
| "play my favorites" | `reference: 'my'` → resolves to the user's collection | no collection signal → searched as plain text; reach favorites by **browsing** the Favorites tab instead |
| "play «App»" | recognised as a resume | searched literally (no app-name heuristic) |
| bare "play" / "resume" | resumes the current/last track | separate resume path (`onPlay`), not a search |
| "play music" (no query) | may send `mode: 'music'` | `mode: 'any'` → return smart-shuffle / recent content |
The gaps are all iOS-only conveniences — collection-by-voice and resume-by-name. Everything in the shared column is fully cross-platform.
## Playing the user's own collection {#playing-the-users-own-collection}
When the user says **"play my favorites"**, the intent carries `reference: 'my'`. Resolve it however your collection lives:
**Local collection** — read `params.reference` in a callback and return your own tracks:
```ts
configureBrowser({
search: async (params) => {
// getFavorites returns your local Track[]
if (params.reference === 'my') return getFavorites(params)
return searchByQuery(params)
}
})
```
**Server collection** — when you use the HTTP form, `reference=my` is appended to `request.query`, so branch in `transformSync` to route the request — for example, to a favorites endpoint, injecting locally-stored identifiers:
```ts
configureBrowser({
search: {
baseUrl: 'https://api.example.com/search',
transformSync(request) {
// `transformSync` runs for every search — pass normal queries straight
// through to /search; only "play my favorites" is rewritten below.
if (request.query?.reference !== 'my') return request
return {
...request,
method: 'POST',
path: '/search/favorites',
contentType: 'application/json',
body: JSON.stringify({
q: request.query.q,
ids: getLocalFavoriteIds() // your stored identifiers
})
}
}
}
})
```
`reference` is only ever `'my'` or `'unknown'` — "currently playing" ("play this") is resolved natively as a resume and never reaches search.
## Voice phrase → params
These mappings are **illustrative, not guaranteed.** The assistant (Siri / Google Assistant) decides how to parse a spoken phrase, and the same words can arrive structured differently — or as a bare `query` — depending on the platform, locale, and the assistant's own interpretation.
Treat the table as *plausible* shapes to handle, and always write your resolver against the fields actually present (see [Cross-platform differences](#cross-platform-differences)) rather than assuming a phrase produces a specific shape.
| Phrase | Resulting `SearchParams` |
| --------------------- | ------------------------------------------------------------- |
| "play something" | `{ mode: 'any', query: '' }` |
| "play music" | `{ mode: 'any', query: '' }` *(iOS may send `mode: 'music'`)* |
| "play jazz" | `{ genre: 'jazz', query: 'jazz' }` |
| "play The Stalk 88.5" | `{ mode: 'station', query: 'The Stalk 88.5' }` |
| "play a jazz podcast" | `{ mode: 'podcast', genre: 'jazz' }` |
| "play my favorites" | `{ reference: 'my', query: '' }` |
| "play my jazz" | `{ reference: 'my', genre: 'jazz' }` |
## Mixed audio/video
This is an **audio** library — its player streams audio and has no video surface, and CarPlay / Android Auto forbid video playback while driving. So video is fundamentally an **in-app** concern: a search can *signal* a video request (via the video `mode` values), but the library will not render video.
To play video from your in-app search, intercept the load with [`handleTrackLoad`](/api/types/browser/#handletrackload). It runs whenever a track is loaded through [`navigate(track)`](/api/features/browser/#navigate) (or the library's own browse UI) — so route your in-app search-result taps through `navigate(track)` rather than calling `setQueue` / `play` yourself, or this hook never fires.
When set, it is called **instead of** the library auto-playing the track — for **every** such load, not just video — so your handler must either route the track elsewhere or hand it back to the library to play:
```ts
import {
configureBrowser,
setQueue,
play,
type Track
} from 'react-native-audio-browser'
// You build the search-result tracks, so encode "this is video" however
// you like. `src` can be any string you recognise later — here, a scheme
// prefix your own player understands.
const isVideo = (track: Track) => track.src?.startsWith('video:') ?? false
configureBrowser({
handleTrackLoad: async ({ track, queue, startIndex }) => {
if (isVideo(track)) {
openVideoPlayer(track) // your own video surface
return
}
setQueue(queue, startIndex) // hand audio back to the library
play() // setQueue does not start playback, so play() is required
}
})
```
The `mode` you saw at **search** time (`music-video` / `movie` / …) is not carried onto the `Track`, and `handleTrackLoad` runs at **load** time with no `mode`.
The tracks your `search` source returns for a video request are *yours*, though — so tag them with a recognizable `src` (as above) when you build them, and read that tag in `isVideo` here.
On external surfaces (CarPlay / Android Auto), a video request falls back to audio or is declined — there is no video playback path there.
---
---
url: https://audiobrowser.dev/guide/audio-output.md
description: >-
Read where audio is currently playing (speaker, Bluetooth, AirPlay, the car),
react when the route changes, and open the system output switcher.
---
# Audio Output
Read where audio is currently playing (speaker, Bluetooth, AirPlay, the car…),
react when it changes, and open the system output switcher so the listener can
move playback to another device. Both layers are **cross-platform**:
* **Reading the current output** — `getOutput()` / `useOutput()` /
`onOutputChanged`. iOS reports the active route while a session is active.
Android reports the device media is routed to; below Android 13 it can miss a
reroute made while a device stays connected.
* **Opening the switcher** — `openOutputPicker()` / `supportsOutputSwitcher()`:
the system route picker on iOS, the system Output Switcher on Android 11+.
::: tip Gate the switcher button on `supportsOutputSwitcher()`
Surface your output button only when `supportsOutputSwitcher()` is `true` — it's
`true` on iOS and Android 11+ (API 30), `false` on older Android and web.
Reading the current output works more broadly, but `getOutput()` can still be
`undefined` (before playback, or when unknown) — so guard for it.
:::
The UI snippets import `Text` / `Button` from `react-native`; everything else is
from `react-native-audio-browser`.
## The current output
[`useOutput()`](/api/features/output/#useoutput) returns the active output and
re-renders whenever it changes (AirPods connect, headphones unplug, a Bluetooth
speaker is selected):
```tsx
import { Text } from 'react-native'
import { useOutput } from 'react-native-audio-browser'
function OutputLabel() {
const output = useOutput()
if (!output) return null // not yet known
return Playing on {output.name}
}
```
An [`Output`](/api/features/output/#output) is:
| Field | Type | Meaning |
| ---------- | ------------ | ------------------------------------------------------------------------------- |
| `name` | `string` | Human-readable device name, e.g. `"AirPods Pro"`, `"Kitchen speaker"`. |
| `type` | `OutputType` | The output kind (see below). |
| `external` | `boolean` | `false` only for the built-in speaker/receiver; `true` for everything external. |
`type` is one of `'speaker'`, `'receiver'` (the built-in earpiece),
`'headphones'`, `'bluetooth'`, `'airplay'`, `'car'`, `'hdmi'`, `'usb'`, `'cast'`
and `'sonos'` (see below), `'remote'` (a remote speaker or TV, see below), or
`'other'`. Both platforms map their native ports/routes into this shared set —
e.g. iOS's separate Bluetooth ports all collapse to `'bluetooth'`.
::: warning Android below 13 can miss a reroute
On Android 13+ (API 33), the output is the device media is routed to. Below
that, the library picks from the connected devices: Bluetooth, then wired
headphones, then the speaker. It misses a reroute made while a device stays
connected.
:::
`'airplay'` and `'car'` come from iOS only. On Android, a car's Bluetooth
reports `'bluetooth'`.
Outside React, read a snapshot with `getOutput()` or subscribe with
[`onOutputChanged`](/api/features/output/#onoutputchanged):
```ts
import { getOutput, onOutputChanged } from 'react-native-audio-browser'
getOutput() // Output | undefined
const unsubscribe = onOutputChanged.addListener((output) => {
console.log('now playing on', output.name)
})
// later:
unsubscribe()
```
### Remote outputs (Android)
With `remoteOutputs: {}` in [`setupPlayer`](/guide/configuration), the system
Output Switcher (Android 11+) also lists the speakers and TVs of media route
providers, and the one the listener selects becomes the output, with
`type: 'remote'`.
While one is selected, the switcher offers **Stop casting**
rather than the phone's own outputs; stopping reports the local device again.
The switcher moves the session only for an app that declares AndroidX's
`MediaTransferReceiver` in its own manifest. The library leaves it out, because
it turns on transfer for any MediaRouter in the app, Cast's included:
```xml
```
Without it, the switcher lists only the phone's own outputs, and the library
logs a warning saying the receiver is missing.
Each `setupPlayer` sets the remote outputs: a call that leaves `remoteOutputs`
out turns them off, and playback on one comes back to the phone.
A provider offers its routes by declaring the library's control category,
`"com.audiobrowser.CATEGORY_REMOTE_OUTPUT"` (`RemoteOutputs.CATEGORY` in
Kotlin), in its control filters. Only the
selection is reported: the library keeps playing locally, and rendering the
audio on the speaker is the provider's job.
`RemoteOutputs.routeDescriptorBuilder(id, name)` starts a route's descriptor
in the category and visible only to the app, from Android 14. Another app on the
library would otherwise list the route too, and report it as its output while
its own playback stays on the phone:
```kotlin
val speaker =
RemoteOutputs.routeDescriptorBuilder("kitchen", "Kitchen")
.setPlaybackType(MediaRouter.RouteInfo.PLAYBACK_TYPE_REMOTE)
.setDeviceType(MediaRouter.RouteInfo.DEVICE_TYPE_SPEAKER)
.setEnabled(true)
.build()
```
Before Android 14 every app lists the route regardless. A provider that serves
only its own app returns `null` from `onCreateRouteController(routeId, options)`
when `options.clientPackageName` is another package, as the library's Sonos
provider does: the other app's switch then fails.
### Google Cast (Android)
With `remoteOutputs: { cast: true }`, selecting a Cast device in the switcher
moves playback there, through Google's Default Media Receiver, or the receiver
`castReceiverApplicationId` names. The output reports `type: 'cast'`.
The queue, the position and the play intent move across both ways: **Stop
casting** brings playback back to the phone, at the same track.
```ts
await setupPlayer({ remoteOutputs: { cast: true } })
```
Cast is opt-in at build time, so apps that don't cast don't ship Google Play
services' Cast framework. Turn it on in the app's `gradle.properties`:
```properties
# android/gradle.properties
AudioBrowser_castEnabled=true
```
The device and its notifications show the receiver's name: "Default Media
Receiver" for Google's. To show the app's own, register a Styled Media Receiver
in the [Google Cast SDK Developer Console](https://cast.google.com/publish) and
pass its ID; Cast takes it once per app process, so a change takes effect after
a restart:
```ts
await setupPlayer({
remoteOutputs: { cast: true, castReceiverApplicationId: 'ABCD1234' }
})
```
The app also declares `MediaTransferReceiver`, as above. Without the build
property, or on a device without Google Play services, playback stays on the
phone and the library logs a warning.
The receiver fetches the stream itself:
* It gets the URL the `media` request config resolves the track's `src` to
(your Transform and Resolve included), without its headers. A stream that
needs request headers won't play on it.
* A track without a file extension is sent as `audio/mpeg`; the receiver works
out the real codec. A track with `live: true` loads as a live stream.
* The receiver shows the track's title, artist and artwork. It doesn't read
song titles from the stream, so the live song doesn't update while casting.
While casting, what only makes sense on the phone steps aside:
* `setVolume` moves the receiver's volume;
* the equalizer and the skip-silence setting wait for playback to come back;
* the sleep timer pauses the receiver without fading;
* load retries and stall recovery are the receiver's own, and a receiver error
reaches the app as a playback error.
Known limits:
* No live song titles on the receiver or the phone while casting: the Default
Media Receiver keeps the metadata it was loaded with.
* The receiver is one that takes the same media as the Default Media Receiver:
Google's own, or a Styled Media Receiver registered for the app.
* Android only. On iOS, the route picker lists AirPlay devices.
* A receiver error is not retried; the app decides what to do with it.
### Sonos (Android)
With `remoteOutputs: { sonos: true }`, the switcher lists the Sonos rooms on the
local network, and selecting one moves playback there. The output reports
`type: 'sonos'` and the room's name.
```ts
await setupPlayer({ remoteOutputs: { sonos: true } })
```
The app declares `MediaTransferReceiver`, as above, and the permission to hold
a Wi-Fi multicast lock while it looks for rooms. No build property is needed:
the library talks to the speakers itself.
```xml
```
Without the permission, the library logs a warning and looks for rooms without
the lock, so a room can be missed while the phone saves power on Wi-Fi.
Local network access: the library finds and controls the rooms itself, over
the local network. An app that targets SDK 36 or lower has that access through
`INTERNET`, and needs nothing more.
From target SDK 37 (Android 17), Android blocks the local network until the
app is granted the runtime permission `ACCESS_LOCAL_NETWORK`. The library
doesn't request it, so request it in your app: without it, rooms don't appear
and can't be controlled. For what Android exempts, see its
[local network permission](https://developer.android.com/privacy-and-security/local-network-permission).
::: warning Sonos support is a bonus, not a promise
The library controls the speakers over UPnP, on port 1400 of each speaker.
Sonos calls UPnP unsupported and unmaintained, and lets the listener switch it
off in the Sonos app. When it is off, or Sonos removes it, the rooms don't
appear in the switcher.
The library doesn't use Sonos's cloud or local Control APIs, which need
Sonos's approval.
:::
What plays:
* The speaker fetches the stream itself, from the URL the `media` request
config resolves the track's `src` to (your Transform and Resolve
included), without its headers.
* A live stream goes as a radio stream: the speaker follows redirects and works
out the codec, so MP3, AAC and HLS streams play, over `https` and plain
`http`.
* A track goes as a file, in a format the speaker plays, so the speaker
knows its duration and can seek in it.
* The speaker is sent the track's title, artist and artwork to show.
* The speaker reads song titles from the stream (ICY titles, and the ID3 titles
of HLS streams). The library polls them and reports them through
`onTimedMetadata`, as it does for local playback, so the live song keeps
updating.
* Play, pause, skip and the volume act on the speaker. A live stream that
refuses to pause is stopped instead, and playing it again restarts it.
* A track shows the position and duration the speaker reports.
* Pausing or stopping in the Sonos app shows up as paused here.
Grouping:
* The switcher lists rooms, not speakers. A stereo pair or a home theatre is one
room.
* Rooms grouped in the Sonos app are listed once, named after the room that
leads the group: "Kitchen + 2". Playing there plays in every room of the group,
and the volume is the group's, as the Sonos app's group volume is.
* The library doesn't group or ungroup rooms; the listener does that in the
Sonos app.
While on Sonos, local-only behaviour steps aside as it does for Cast. The
volume is the speaker's, and the equalizer waits for the phone. A speaker error
reaches the app as a playback error, as does a speaker that stops answering.
Known limits:
* Rooms are found by SSDP multicast on the local network, so the phone and the
speakers must share it; guest and isolated Wi-Fi networks hide them.
* A track that needs request headers won't play.
* The state is polled, so a change made in the Sonos app shows up here after a
moment.
* If another app or the Sonos app starts something else on the room, this app
reads as paused and leaves the room alone; playing again loads its own track.
* Android only. On iOS, a Sonos speaker with AirPlay 2 appears in the route
picker as an AirPlay target.
### On every remote output
Cast and Sonos play the queue the same way:
* The queue stays in the app. The receiver is sent one item at a time, at the
position it plays from, and the app sends the next when one ends, as the
repeat mode says. Editing the queue reaches the receiver only when the
current item changes.
* The shuffle mode is kept and comes back to the phone, but a remote output
plays the queue in list order
([#210](https://github.com/radio-garden/react-native-audio-browser/issues/210)).
* Selecting an output moves the queue, the position, the play intent and the
repeat mode there. The phone plays on until the current item's URL is
resolved for the receiver, and the output already reports `'cast'` or
`'sonos'` meanwhile.
* Moving from one room or Cast device to another goes straight there, without
the phone in between.
* A receiver that fails to play reaches the app as a playback error with code
`remote-error`. So does an item whose URL can't be resolved for it, and one
the receiver hasn't started within 30 seconds of being sent or played.
Playing again loads the item there anew.
The library's Sonos route provider service is exported, as the Output Switcher
needs to bind it: another app on the phone can bind it too and list the rooms,
but the provider serves only the app's own sessions, so another app can't
select a room. Only an app that bypasses Android's hidden-API restrictions can
still set the volume of a room the app plays to.
When a Sonos room that another app's provider serves is selected, the library
unselects it: the output stays the phone, and the switcher stops offering
**Stop casting** for it.
## Opening the output picker
[`openOutputPicker()`](/api/features/output/#openoutputpicker) presents the
system output switcher — the AirPlay / Bluetooth / speaker chooser on iOS, and
the Bluetooth / speaker / Cast switcher on Android (11+). Wire it to your own
output button, shown only when
[`supportsOutputSwitcher()`](/api/features/output/#supportsoutputswitcher) is
`true`:
```tsx
import { Button } from 'react-native'
import {
openOutputPicker,
supportsOutputSwitcher
} from 'react-native-audio-browser'
function OutputButton() {
if (!supportsOutputSwitcher()) return null // older Android / web
return openOutputPicker()} />
}
```
`openOutputPicker()` is safe to call unconditionally — it's a no-op where no
switcher exists — but gating the button on `supportsOutputSwitcher()` keeps you
from showing a control that would do nothing.
On Android the switcher is the system one (the picker from the media
notification); selecting a Bluetooth speaker there routes audio at the OS level.
The library can't force playback to a *specific* Bluetooth device itself — route
selection is the system's job, which is what this hands off to.
Sonos appears on
iOS as an AirPlay target, and on Android with `remoteOutputs: { sonos: true }`.
## You may not need this for unplug handling
When the current output **disappears** — headphones unplugged, a Bluetooth
speaker powered off — the player **pauses automatically** rather than blaring out
of the built-in speaker (the convention every media app follows). It's a
deliberate pause: the listener presses play again when ready.
So you don't need
to watch `onOutputChanged` just to handle unplugging — reach for these APIs to
*display* the output or to *offer* a switcher.
On Android, `setupPlayer({ android: { handleAudioBecomingNoisy: false } })`
turns the pause off. On iOS it always happens.
## API summary
| API | Platforms | Purpose |
| -------------------------- | ---------------- | -------------------------------------------------------------------------- |
| `openOutputPicker()` | iOS, Android 11+ | Present the system output switcher (Bluetooth / AirPlay / speaker / Cast). |
| `supportsOutputSwitcher()` | all | Whether a switcher can be shown — gate your output button on it. |
| `useOutput()` | iOS, Android | Reactive current output (`Output \| undefined`). |
| `getOutput()` | iOS, Android | One-off snapshot of the current output. |
| `onOutputChanged` | iOS, Android | Subscribe outside React; `addListener(cb)` returns an unsubscribe fn. |
The whole API is cross-platform; only the switcher needs Android 11+ (gate on
`supportsOutputSwitcher()`). Below Android 13, the output can miss a reroute
made while a device stays connected.
---
---
url: https://audiobrowser.dev/guide/battery.md
description: >-
Detect the Android 12+ battery restrictions that block the foreground service
the player needs, and prompt the listener to fix their settings.
---
# Battery
On Android 12+, if the OS has put your app under battery restrictions, it
**blocks the foreground service** the player needs to start audio in the
background. So when a Bluetooth device or car head unit tries to resume playback
while your app is killed, nothing happens.
This feature detects that block and lets you prompt the user to fix their
battery settings.
::: warning Android only
This is an **Android-only** concern (Android 12+ foreground-service limits).
On iOS every getter/hook here is inert: `getBatteryWarningPending()` is always
`false`, `getBatteryOptimizationStatus()` is always `'unrestricted'`, the events
never fire, and `dismissBatteryWarning()` / `openBatterySettings()` are no-ops.
So you can render the banner below unconditionally: it never shows on iOS.
:::
## The warning banner
A warning becomes **pending** when a background resume is actually blocked. The
block happens while your app is killed, so the library saves the warning and you
see it the next time the app opens. It stays pending across launches until it
clears.
Show a banner only while `pending` is true, offering to open settings or
dismiss. [`useBatteryWarning()`](/api/features/battery/#usebatterywarning)
bundles everything you need:
```tsx
import { View, Text, Button } from 'react-native'
import { useBatteryWarning } from 'react-native-audio-browser'
function BatteryWarningBanner() {
const { pending, status, dismiss, openSettings } = useBatteryWarning()
if (!pending) return null
return (
Playback was blocked by battery settings ({status}).
)
}
```
* `openSettings` ([`openBatterySettings`](/api/features/battery/#openbatterysettings))
depends on the status. When it is `'optimized'`, it asks the system for the
dialog that lets the user exempt the app from battery optimization in one tap.
This works only if your app declares the permission below.
With any other status, `'restricted'` included, it opens the app's App info
page, and the user changes the battery setting from there. When the user
returns having set the app to unrestricted, the warning clears itself.
* `dismiss` ([`dismissBatteryWarning`](/api/features/battery/#dismissbatterywarning))
hides the warning without changing settings.
::: warning The one-tap dialog needs a permission
The library doesn't declare `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`. Without it,
Android drops the dialog request in the `'optimized'` state: nothing appears,
and the status stays `'optimized'`. The library doesn't detect this or fall
back to another settings page.
To get the dialog, declare the permission in your app:
```xml
```
Google Play restricts which apps may declare this permission. Check its policy
before you add it. If you can't declare it, send users in the `'optimized'`
state to the system battery settings some other way.
:::
## When the warning clears
`pending` goes back to `false` when any of these happens — you don't clear it
manually:
* your app calls `dismiss` (for example, when the user taps Dismiss), or
* the battery status becomes `'unrestricted'` (e.g. they fixed it in settings).
## Battery optimization status
`status` is the device's current setting for your app:
| Status | Meaning |
| ---------------- | -------------------------------------------------------------------- |
| `'unrestricted'` | The user allowed the app to run freely in the background. |
| `'optimized'` | Default — the system may limit background work (Doze / App Standby). |
| `'restricted'` | Background work is severely limited; services are blocked. |
Background resume is reliable only when `'unrestricted'`, which is why the "Fix"
button sends users to settings to grant it.
## Reading state directly
If you don't want the bundled hook, the pieces are available individually:
```ts
import {
getBatteryWarningPending,
getBatteryOptimizationStatus,
onBatteryWarningPendingChanged,
onBatteryOptimizationStatusChanged
} from 'react-native-audio-browser'
getBatteryWarningPending() // boolean
getBatteryOptimizationStatus() // 'unrestricted' | 'optimized' | 'restricted'
const off = onBatteryWarningPendingChanged.addListener(({ pending }) => {})
const off2 = onBatteryOptimizationStatusChanged.addListener(({ status }) => {})
// each addListener returns an unsubscribe function:
off()
off2()
```
The reactive hooks [`useBatteryWarningPending()`](/api/features/battery/#usebatterywarningpending)
and [`useBatteryOptimizationStatus()`](/api/features/battery/#usebatteryoptimizationstatus)
wrap the getter+event pairs; `useBatteryWarning()` simply combines both with the
two actions.
## API summary
| API | Purpose |
| ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `useBatteryWarning()` | Everything for a banner: `{ pending, status, dismiss, openSettings }`. |
| `getBatteryWarningPending()` / `useBatteryWarningPending()` | Is a warning pending? (Android; `false` on iOS) |
| `getBatteryOptimizationStatus()` / `useBatteryOptimizationStatus()` | Current status (Android; `'unrestricted'` on iOS) |
| `onBatteryWarningPendingChanged` / `onBatteryOptimizationStatusChanged` | Subscribe outside React. |
| `openBatterySettings()` | Prompt the user to lift the restriction (Android; see above for the permission the `'optimized'` dialog needs). |
| `dismissBatteryWarning()` | Dismiss the warning without changing settings (Android). |
---
---
url: https://audiobrowser.dev/guide/equalizer.md
description: >-
Shape playback tone with the Android system equalizer: named presets, custom
band levels, and handling its absence on iOS and web.
---
# Equalizer
The equalizer lets you shape playback tone — boost the bass, tame the treble —
either by applying a named **preset** (e.g. "Rock", "Jazz") or by setting
**custom band levels** yourself. It wraps the system equalizer effect.
::: warning Android only
The equalizer is **Android-only**. On iOS and web every getter returns
`undefined` and every setter is a no-op; neither platform has an equivalent
system equalizer. Always treat the settings as possibly-absent (see
[Availability](#availability)).
:::
The UI snippets below import `View` / `Text` / `Button` from `react-native` and
`Slider` from `@react-native-community/slider`; those import lines are omitted
for brevity. Everything else comes from `react-native-audio-browser`.
## Availability
[`getEqualizerSettings()`](/api/features/equalizer/#getequalizersettings)
returns [`EqualizerSettings | undefined`](/api/features/equalizer/#equalizersettings).
It's `undefined` whenever the equalizer isn't available: on iOS and web, and
**on Android before `setupPlayer`** and for a short moment after it, until the
player's audio session arrives. Use the reactive hook so a settings screen fills
in when it does.
On Android, a setter called after `setupPlayer` but before the equalizer exists
is kept and applied when it appears; the result arrives through
`onEqualizerChanged`. A setter called before `setupPlayer` is dropped.
## Reading the settings
[`useEqualizerSettings()`](/api/features/equalizer/#useequalizersettings) returns
the current settings and re-renders when they change:
```tsx
import { useEqualizerSettings } from 'react-native-audio-browser'
function EqualizerStatus() {
const eq = useEqualizerSettings()
if (!eq) return Equalizer unavailable
return (
{eq.enabled ? 'On' : 'Off'} · {eq.bandCount} bands
)
}
```
The [`EqualizerSettings`](/api/features/equalizer/#equalizersettings) object:
| Field | Type | Meaning |
| ----------------------- | --------------------- | ----------------------------------------------------- |
| `enabled` | `boolean` | Whether the effect is currently applied. |
| `bandCount` | `number` | Number of frequency bands. |
| `bandLevels` | `number[]` | Current level per band, in **millibels**. |
| `centerBandFrequencies` | `number[]` | Center frequency per band, in **milliHertz**. |
| `lowerBandLevelLimit` | `number` | Minimum level (millibels) any band accepts. |
| `upperBandLevelLimit` | `number` | Maximum level (millibels) any band accepts. |
| `presets` | `string[]` | Available preset names. |
| `activePreset` | `string \| undefined` | The applied preset, or `undefined` for custom levels. |
See [the units note](#a-note-on-units) — both level and frequency values use
"milli" units.
Outside React, read a snapshot with `getEqualizerSettings()` or subscribe with
[`onEqualizerChanged`](/api/features/equalizer/#onequalizerchanged).
All the `setEqualizer*` calls below are fire-and-forget — they return `void`.
The updated settings come back through `useEqualizerSettings` /
`onEqualizerChanged`, not as a return value.
## Turning it on
The effect does nothing audible until it's enabled. Toggle it with
[`setEqualizerEnabled`](/api/features/equalizer/#setequalizerenabled):
```ts
import { setEqualizerEnabled } from 'react-native-audio-browser'
setEqualizerEnabled(true)
```
## Applying a preset
[`setEqualizerPreset`](/api/features/equalizer/#setequalizerpreset) takes one of
the names from `settings.presets`. The match is case-insensitive; an unknown
name is ignored (a warning is logged), so drive your UI from the actual
`presets` list rather than hard-coded strings:
```tsx
import {
setEqualizerPreset,
useEqualizerSettings
} from 'react-native-audio-browser'
function PresetPicker() {
const eq = useEqualizerSettings()
if (!eq) return null
return (
{eq.presets.map((preset) => (
setEqualizerPreset(preset)}
/>
))}
)
}
```
After applying a preset, `activePreset` reflects it. Available presets come from
the device's system equalizer, so the exact list varies by device.
## Custom band levels
[`setEqualizerLevels`](/api/features/equalizer/#setequalizerlevels) sets every
band at once, in **millibels**. The array length **must equal `bandCount`** — a
mismatched array is ignored — and each value should fall within
`lowerBandLevelLimit … upperBandLevelLimit`:
```ts
import { setEqualizerLevels } from 'react-native-audio-browser'
// Flatten all bands to 0, then boost the lowest band by 6 dB (600 mB).
const flat = new Array(eq.bandCount).fill(0)
flat[0] = 600
setEqualizerLevels(flat)
```
Setting custom levels clears `activePreset` (it becomes `undefined`), even if
they equal a preset's levels. To return to a preset, apply it again.
Whichever you applied last, preset or custom levels, carries over to the next
audio session, along with the enabled state.
## A complete equalizer screen
Guard for availability, then render an enable toggle, the device presets, and a
slider per band:
```tsx
import { View, Text, Button } from 'react-native'
import Slider from '@react-native-community/slider'
import {
useEqualizerSettings,
setEqualizerEnabled,
setEqualizerPreset,
setEqualizerLevels
} from 'react-native-audio-browser'
// Center frequencies are milliHertz; levels are millibels (1/100 dB).
const formatHz = (mHz: number) => {
const hz = mHz / 1000
if (hz < 1000) return `${hz.toFixed(0)} Hz`
return `${(hz / 1000).toFixed(hz >= 10000 ? 0 : 1)} kHz`
}
function EqualizerScreen() {
const eq = useEqualizerSettings()
if (!eq) return Equalizer not available
const setBand = (index: number, millibels: number) => {
const next = [...eq.bandLevels]
next[index] = millibels
setEqualizerLevels(next)
}
return (
setEqualizerEnabled(!eq.enabled)}
/>
{eq.presets.map((preset) => (
setEqualizerPreset(preset)}
/>
))}
{eq.centerBandFrequencies.map((mHz, index) => {
const level = eq.bandLevels[index] ?? 0
return (
{formatHz(mHz)}: {(level / 100).toFixed(1)} dB
setBand(index, millibels)}
/>
)
})}
)
}
```
If the thumbs don't follow a newly applied preset, give each `Slider` a
`key={eq.activePreset}` so it remounts with the new levels.
## A note on units
The system equalizer works in "milli" units, so convert for display:
* **Levels** (`bandLevels`, the limits, and what you pass to
`setEqualizerLevels`) are in **millibels** — hundredths of a decibel. `600`
mB = 6 dB; divide by 100 for dB.
* **Center frequencies** (`centerBandFrequencies`) are in **milliHertz**.
`60000` = 60 Hz; divide by 1000 for Hz.
## API summary
| API | Purpose |
| --------------------------------------------------- | --------------------------------------------- |
| `useEqualizerSettings()` / `getEqualizerSettings()` | Read settings (`undefined` if unavailable). |
| `onEqualizerChanged` | Subscribe to settings changes outside React. |
| `setEqualizerEnabled(bool)` | Turn the effect on or off. |
| `setEqualizerPreset(name)` | Apply a preset from `settings.presets`. |
| `setEqualizerLevels(millibels[])` | Set all bands; length must equal `bandCount`. |
All are **Android-only**: no-ops or `undefined` on iOS and web.
---
---
url: https://audiobrowser.dev/guide/network.md
description: >-
Track the device's internet connectivity with useOnline, getOnline, and
onOnlineChanged, and what "online" means on each platform.
---
# Network
The library tracks the device's internet connectivity with a platform monitor and
exposes it three ways:
* [`useOnline()`](/api/features/network/#useonline) — a reactive hook for your UI.
* [`getOnline()`](/api/features/network/#getonline) — a one-off snapshot.
* [`onOnlineChanged`](/api/features/network/#ononlinechanged) — subscribe to
changes outside React.
All three report the same boolean, but each platform decides it differently:
* **Android** asks the OS whether the default network offers internet. It does
not wait for the OS to validate it, so a network that never validates (a
failing Private DNS, some hotspots) reads `true`, and so can a captive or
dead Wi-Fi.
* **iOS** reads the system path monitor (`NWPathMonitor`), which reports
whether a usable network path exists. It does not check that the internet is
reachable, so a captive or dead Wi-Fi can read `true`.
* **Web** reads `navigator.onLine` and the window's `online` and `offline`
events, which only say whether a network interface is up.
::: warning Android: only after setupPlayer()
On Android the connectivity monitor belongs to the player, so it runs only once
`setupPlayer()` has connected the player service.
Before that, and while the service restarts, `getOnline()` and `useOnline()`
read `true` even when the device is offline, and `onOnlineChanged` doesn't
fire. Once the service connects, `onOnlineChanged` fires with the current
state. iOS and web report the real state from the start.
:::
## In your UI
`useOnline` re-renders when connectivity flips — enough for an offline banner:
```tsx
import { Text } from 'react-native'
import { useOnline } from 'react-native-audio-browser'
function OfflineBanner() {
const online = useOnline()
if (online) return null
return You're offline
}
```
## Outside React
Read a snapshot with `getOnline()`, or subscribe with `onOnlineChanged`
(`addListener` returns an unsubscribe function):
```ts
import { getOnline, onOnlineChanged } from 'react-native-audio-browser'
getOnline() // → true | false
const unsubscribe = onOnlineChanged.addListener((online) => {
if (online) refetchSomething()
})
// later:
unsubscribe()
```
## You may not need this
The player already reacts to connectivity on its own, so you usually don't wire
these up for playback:
* When the connection drops mid-stream, the now-playing formatter receives
`stalled: 'offline'` (vs `'buffering'` when online) — see
[Now Playing → the formatter](/guide/now-playing#the-formatter-derived-continuous).
* On iOS, when the connection returns while the stream sits **stalled** (state
`'buffering'` with play intent), the player re-establishes it automatically:
you don't need to listen for reconnect and re-`play()`.
On Android, most drops surface as a playback **error** instead, and the
reconnect when connectivity returns only runs with
[automatic retry](/guide/errors#automatic-retry)
(`setupPlayer({ retry })`, off by default) enabled. See
[Live streams → Dropouts](/guide/live-streams#dropouts-stalls-and-retry).
Once retry gives up, or without it, the player stays in `'error'` until the
listener (or your code) calls `retry()` or `play()`.
Reach for `useOnline` / `onOnlineChanged` for **your own** UI and data — an
offline banner, disabling a control, refetching a list on reconnect.
## API summary
| API | Purpose |
| ----------------- | --------------------------------------------------------------------- |
| `useOnline()` | Reactive `boolean`; re-renders on connectivity change. |
| `getOnline()` | One-off snapshot `boolean` (`true` on Android before setup). |
| `onOnlineChanged` | Subscribe outside React; `addListener(cb)` returns an unsubscribe fn. |
`true` = online by the platform's definition above; `false` = offline
(including a network with no internet behind it on Android).
---
---
url: https://audiobrowser.dev/guide/sleep-timer.md
description: >-
Pause playback after a fixed time or at the end of the current track, counted
down natively so it fires with the app backgrounded or the screen off.
---
# Sleep Timer
A **sleep timer** pauses playback on its own after a set time — the classic
"fall asleep to the radio" feature. The library runs the timer natively, so it
keeps counting down and fires even when your app is backgrounded or the screen
is off. There are two kinds:
* **Time-based** — pause after a fixed number of seconds (e.g. "in 30 minutes").
* **End of track** — pause when the current track finishes playing (see
[Behavior and edge cases](#behavior-and-edge-cases) for skips and repeat).
Only one timer is active at a time; setting a new one replaces the old.
## Setting a timer
Call `setSleepTimer` with a duration in **seconds**. This example pauses
playback after 30 minutes:
```ts
import { setSleepTimer } from 'react-native-audio-browser'
setSleepTimer(30 * 60)
```
Most UIs offer a few presets rather than a free-form duration — multiply the
minutes you show by 60:
```ts
const PRESETS_MINUTES = [15, 30, 45, 60] as const
setSleepTimer(PRESETS_MINUTES[1] * 60) // 30 minutes
```
To pause when the current track ends instead of after a fixed time, use
`setSleepTimerToEndOfTrack`:
```ts
import { setSleepTimerToEndOfTrack } from 'react-native-audio-browser'
setSleepTimerToEndOfTrack()
```
When the timer completes, the library **pauses** playback (it doesn't stop or
tear the player down). Pressing play resumes as normal.
## Fading out
Pass a `fadeDuration` (in seconds) to ramp the volume down to silence as the
timer runs out — a gentler finish than an abrupt pause:
```ts
// Pause in 30 minutes, fading the last 20 seconds to silence.
setSleepTimer(30 * 60, { fadeDuration: 20 })
```
The fade always ends exactly at the deadline (if `fadeDuration` is longer than
the timer itself, it's clamped to the timer's length). Once playback pauses, the
library restores the pre-fade volume, so the next time the listener hits play it
starts at normal loudness.
During the fade the timer takes priority: seeking or skipping plays into the
remaining ramp rather than cancelling it. Only pausing, or clearing/replacing
the timer, stops the fade.
The countdown keeps ticking throughout, so you can show a "fading out" hint
once `secondsLeft` drops to `fadeDuration` (see the
[complete example](#a-complete-screen)).
While casting on Android, the timer pauses the receiver at the deadline without
fading: see [Google Cast](/guide/audio-output#google-cast-android).
## Clearing a timer
`clearSleepTimer` cancels the active timer. It returns `true` if a timer was
actually cleared, or `false` if none was set:
```ts
import { clearSleepTimer } from 'react-native-audio-browser'
clearSleepTimer()
```
## Reading the timer in your UI
Use the `useSleepTimer` hook to show a live countdown. It re-renders every
second and returns:
* For a time-based timer: `{ time, secondsLeft }`, where `time` is the deadline
(epoch milliseconds) and `secondsLeft` counts down to `0`.
* For an end-of-track timer: `{ sleepWhenPlayedToEnd: true }`.
* `undefined` when no timer is active.
```tsx
import { useSleepTimer } from 'react-native-audio-browser'
function SleepTimerLabel() {
const timer = useSleepTimer()
if (!timer) return No sleep timer
if ('sleepWhenPlayedToEnd' in timer) {
return Pausing at end of track
}
const minutes = Math.floor(timer.secondsLeft / 60)
const seconds = timer.secondsLeft % 60
return (
Sleeping in {minutes}m {seconds}s
)
}
```
The countdown only ticks while the app is in the foreground — `secondsLeft`
doesn't advance in the background (the native timer still fires on time
regardless).
The only reason to care is to avoid pointless per-second re-renders while
backgrounded: derive the `inactive` flag from React Native's `AppState` and
pass it in. You can also tune the refresh rate with `updateInterval`
(milliseconds, default `1000`):
```tsx
import { useEffect, useState } from 'react'
import { AppState } from 'react-native'
import { useSleepTimer } from 'react-native-audio-browser'
function useAppInactive() {
const [inactive, setInactive] = useState(
() => AppState.currentState !== 'active'
)
useEffect(() => {
const sub = AppState.addEventListener('change', (state) =>
setInactive(state !== 'active')
)
return () => sub.remove()
}, [])
return inactive
}
// In a component: pause the countdown updates while backgrounded.
const timer = useSleepTimer({ inactive: useAppInactive() })
```
### Just need to know if one is set?
If you only want to toggle a button's appearance, `useSleepTimerActive` is a
lighter-weight hook that returns a boolean and doesn't re-render every second:
```tsx
import { useSleepTimerActive } from 'react-native-audio-browser'
function SleepTimerButton() {
const active = useSleepTimerActive()
return
}
```
## A complete screen
Putting it together — preset durations, an end-of-track option, an off button,
and a live countdown that switches to a "fading out" hint as the fade begins:
```tsx
import { View, Button, Text } from 'react-native'
import {
setSleepTimer,
setSleepTimerToEndOfTrack,
clearSleepTimer,
useSleepTimer
} from 'react-native-audio-browser'
const PRESETS_MINUTES = [15, 30, 45, 60]
const FADE_SECONDS = 20
function SleepTimerScreen() {
const timer = useSleepTimer()
return (
{PRESETS_MINUTES.map((minutes) => (
setSleepTimer(minutes * 60, { fadeDuration: FADE_SECONDS })
}
/>
))}
setSleepTimerToEndOfTrack()}
/>
clearSleepTimer()} />
)
}
function Status(props: {
timer: ReturnType
fadeSeconds: number
}) {
const { timer, fadeSeconds } = props
if (!timer) return No sleep timer
if ('sleepWhenPlayedToEnd' in timer) {
return Pausing at end of track
}
if (timer.secondsLeft <= fadeSeconds) return Fading out…
const minutes = Math.floor(timer.secondsLeft / 60)
const seconds = timer.secondsLeft % 60
return (
Sleeping in {minutes}m {seconds}s
)
}
```
When the timer fires (or is cleared), `useSleepTimer` returns `undefined` and
the countdown stops on its own — so `Status` falls back to "No sleep timer"
without any extra handling on your part.
## Outside of React
If you're not in a component, read the current timer with `getSleepTimer` or
subscribe to changes with `onSleepTimerChanged`. Note that `getSleepTimer`
returns the raw timer state (`{ time }` in epoch milliseconds, or
`{ sleepWhenPlayedToEnd }`, or `null`) — it doesn't compute `secondsLeft`; that
convenience is added by the `useSleepTimer` hook.
```ts
import { getSleepTimer, onSleepTimerChanged } from 'react-native-audio-browser'
getSleepTimer() // { time } | { sleepWhenPlayedToEnd } | null
// addListener returns a cleanup function — call it to unsubscribe.
const unsubscribe = onSleepTimerChanged.addListener((timer) => {
console.log('sleep timer is now', timer)
})
// later, when you no longer need updates:
unsubscribe()
```
## Behavior and edge cases
* **Setting replaces, it doesn't stack.** Calling any setter while a timer is
running swaps it for the new one — there's only ever a single active timer.
* **Not persisted across launches.** The timer lives in memory. If the app is
killed (or the OS reclaims it), the timer is gone on next launch — it does not
resume. Persist your own "timer set at" value if you need to restore the UI.
* **No input validation.** `seconds` is passed straight through to the native
scheduler, which isn't clamped — a value of `0` or a negative number fires
essentially immediately (pausing right away). Validate in your own UI if that
matters.
* **Nothing throws.** Every function here is synchronous; the setters return
`void` and `clearSleepTimer` returns a boolean. No `try/catch` needed.
* **Set it after setup.** On iOS and Android, a setter called before
`setupPlayer` has resolved is ignored without an error, and `getSleepTimer`
stays `null`.
* **End of track when the track changes early, on iOS.** Any change of current
track before it ends (a skip, a new queue) cancels an end-of-track timer, and
`onSleepTimerChanged` fires with `null`.
* **End of track when the track changes early, on Android and web.** The timer
stays set through a skip or a new queue, and it pauses at the end of the next
track that plays to its end.
* **End of track with repeat-track on Android.** While the repeat mode is
`track`, an end-of-track timer never fires on Android, because the track loops
without ending. On iOS and web it pauses at the end of the current
play-through.
## API summary
| API | Purpose |
| ----------------------------------------------- | --------------------------------------------------------------- |
| `setSleepTimer(seconds, { fadeDuration? })` | Pause playback after `seconds`, optionally fading out. |
| `setSleepTimerToEndOfTrack()` | Pause when the current track finishes. |
| `clearSleepTimer()` | Cancel the active timer; returns `true` if one was cleared. |
| `getSleepTimer()` | Read the raw timer state (no `secondsLeft`). |
| `onSleepTimerChanged` | Subscribe to timer changes outside React; returns a cleanup fn. |
| `useSleepTimer({ updateInterval?, inactive? })` | Live state with a `secondsLeft` countdown. |
| `useSleepTimerActive()` | Boolean: is any timer set? |
---
---
url: https://audiobrowser.dev/guide/automotive.md
description: >-
How CarPlay, Android Auto, and Android Automotive all reuse the browse tree,
queue, now-playing metadata, and search source you have already built.
---
# In the car
CarPlay, Android Auto, and Android Automotive all show your content on the car
screen and play through the same player as your app. You don't build a separate
"car app" — the car surfaces are driven by the **same cross-cutting pieces you've
already built**:
* your [browse tree](/guide/browser) becomes the car's browsable menus,
* your [now-playing metadata](/guide/now-playing) fills the car's now-playing
screen,
* the [player and queue](/guide/playback) are shared, so playback is continuous
whether the user started it in-app or in the car,
* your [`search` source](/guide/search) answers in-car voice commands
("play jazz"),
* your [favorites](/guide/favorites) are one state shared by the app and the
car. With `capabilities.favorite` on, Android Auto shows the heart; CarPlay
shows it once you list it in `ios.carPlayNowPlayingButtons` (see
[Favoriting from system controls](/guide/favorites#favoriting-from-system-controls)).
Only Siri understands "play my favorites"; Android Auto searches the phrase
as plain text.
Build those once and they light up every car surface. The per-platform pages
handle the platform-specific **setup**: **[Android Auto](/guide/android-auto)**
(also Android Automotive) and **[CarPlay](/guide/carplay)**.
## Shared vs platform-specific
| Concern | Where it's handled |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Browse tree / menus | Shared — [Browser](/guide/browser) |
| Now-playing metadata & artwork | Shared — [Now Playing](/guide/now-playing) |
| Player, queue, playback | Shared — [Playback](/guide/playback) |
| Voice search ("play …") | Shared — your [`search`](/guide/search) source |
| Favorites state | Shared — [Favorites](/guide/favorites) |
| App setup, entitlements, manifest | Per-platform — [Android Auto](/guide/android-auto) / [CarPlay](/guide/carplay) |
| Now-playing buttons, the heart among them | Per-platform — [Button layout](/guide/remote-controls#button-layout-android) (Android) / [`ios.carPlayNowPlayingButtons`](/guide/carplay#now-playing-buttons) (iOS) |
The takeaway: spend your effort on the shared content model; reach for a platform
page only for that platform's setup and buttons.
## Detecting a car connection
To adapt your in-app UI while connected to a car (a "now playing in your car"
state, a simplified screen), use
[`useCarConnected()`](/api/features/carConnection/#usecarconnected). It's `true`
for a CarPlay connection on iOS, and an Android Auto **or Android Automotive**
connection on Android (`false` on web):
```tsx
import { Text } from 'react-native'
import { useCarConnected } from 'react-native-audio-browser'
function CarBadge() {
const inCar = useCarConnected()
if (!inCar) return null
return Playing in your car
}
```
Outside React, read a snapshot with
[`isCarConnected()`](/api/features/carConnection/#iscarconnected) or subscribe
with [`onCarConnectedChanged`](/api/features/carConnection/#oncarconnectedchanged)
(`addListener` returns an unsubscribe function):
```ts
import {
isCarConnected,
onCarConnectedChanged
} from 'react-native-audio-browser'
isCarConnected() // boolean
const unsubscribe = onCarConnectedChanged.addListener((connected) => {
// ...
})
// later: unsubscribe()
```
## Next steps
1. Set up the platform(s) you ship to —
**[Android Auto](/guide/android-auto)** (and Android Automotive) and/or
**[CarPlay](/guide/carplay)**.
2. Make sure your [browse tree](/guide/browser) and
[now-playing](/guide/now-playing) are in good shape — that's what the car
renders.
3. Wire your [`search` source](/guide/search) so voice commands work in the car.
---
---
url: https://audiobrowser.dev/guide/android-auto.md
description: >-
Put your browse tree and playback on the Android Auto car screen: the
automotive app descriptor, the manifest entries the library merges in, and
"Hey Google, play…" voice search.
---
# Android Auto
## Overview
Android Auto shows your [browse tree](/guide/basic-usage) on the car screen and plays through the same player as your app. Two systems drive it:
1. **Browse tree** — Android Auto reads your content from a `MediaBrowserService`, which mirrors your browser routes. The library ships this service.
2. **Voice search** — "Hey Google, play…" arrives as a `MEDIA_PLAY_FROM_SEARCH` intent, which the library routes to your `search` source.
Unlike CarPlay — which needs entitlements and scene delegates — Android Auto needs almost no app-side code.
The library's own `AndroidManifest.xml` declares the media library service Android Auto binds to, the voice-search intent filter, the content provider that serves browse artwork to the car, and the foreground-service permissions, and those **merge into your app automatically**. You only have to declare your app as an automotive media app.
## Setup
### 1. Declare the automotive app descriptor
Add this `` inside the `` tag of your app's `AndroidManifest.xml`:
```xml
```
### 2. Add the descriptor resource
Create `android/app/src/main/res/xml/automotive_app_desc.xml`:
```xml
```
That's the whole setup.
The rest comes from the [library's manifest](https://github.com/radio-garden/react-native-audio-browser/blob/next/android/src/main/AndroidManifest.xml), which merges into your app, so you don't declare it yourself.
## Voice search
Google Assistant requests ("play some jazz", "play the radishes") arrive as a `MEDIA_PLAY_FROM_SEARCH` intent. The library normalizes it into the same structured `SearchParams` your in-app and Siri searches use and calls your `search` source — no extra manifest setup, since the library declares the intent filter.
Android sends a subset of what iOS does: the query, the `any` / `song` / `playlist` modes, and the genre, artist, album, title and playlist filters, always with `reference: 'unknown'`. See [Search](/guide/search) for how to resolve these requests and the cross-platform differences.
## Browse display
Android Auto reads a page's layout from the **parent item** that opens it — before the page resolves. So the layout is declared in two places: on the parent item (a tab, or a row on another page) and on the page itself.
```ts
// The parent item — a tab, or a row on another page. Android Auto
// reads the layout from here, before the page resolves.
{
title: 'Stations',
path: '/browse/stations',
// layout of the page this opens ('list' is the default)
style: { display: 'grid' },
}
// The page it opens — the ResolvedTrack served for '/browse/stations':
{
path: '/browse/stations',
title: 'Stations',
style: { display: 'grid' }, // the page-wide declaration
children: [ /* the tiles */ ]
}
```
* **`style.display` on the parent item** — `'list'` (rows) or `'grid'` (tiles). Android Auto decides the page's layout from this before the page resolves, and it is only sent when you declare it. Leave it off and AAOS renders the whole page as a list (see the warning below); projected Android Auto still follows the page's and its sections' `display` item by item.
The library logs a warning to Logcat, in debug and release builds, when Android Auto opens an all-grid page whose parent item declares no `display`. (A section's "view all" page needs no declaration of its own: it reuses the section's `style`.)
* **Sections** — declare `sections` on the page to group its tracks under headers; each [`Section`](/api/types/browser-nodes/#section)'s `title` renders as a header above its children. A section that carries a `path` also gets a browsable "view more" row appended after its children, navigating there.
No header is tappable on Android Auto at any `display`, so the row is the only affordance the section's `path` has here; its title comes from the [`viewMoreTitle`](/api/types/browser/#viewmoretitle) browser option — one wording for every section.
For per-section copy (`"View all 42 albums"`), leave `path` unset and append your own browsable `Track` to `children` instead, titled however you like. `children` is shared by every surface, so CarPlay and in-app UIs show that row too; see [`Section`](/api/types/browser-nodes/#section) for how CarPlay draws a section with and without a `path`.
::: warning AAOS lays out the whole page from the parent item's `display`
On AOSP-based Android Automotive units — including mainstream cars' OEM skins — the parent item's `display` is the **only** below-root layout signal honored. The whole page renders as list or grid, uniformly.
Per-section `display` differences (a single-line grid above a list, say) render on CarPlay and projected Android Auto, but an AAOS unit shows the page in the single declared layout.
There is no way to describe a mixed page there — pick the layout that suits its dominant section, or split the content across pages. `gridWrap: false` also has no single-line container there: the grid wraps, showing more, never less.
:::
```ts
sections: [
{
title: 'Live now',
children: [
{ title: 'Morning Show', src: '…' },
{ title: 'Afternoon Drive', src: '…' }
]
},
{ title: 'Up next', children: [{ title: 'Late Night Jazz', src: '…' }] }
]
```
## Now Playing buttons
The buttons on the Now Playing screen come from the same
[`remoteButtonLayout`](/guide/remote-controls#button-layout-android) that drives the
notification — there's no car-specific option. Two behaviors are particular to
the car, though:
* **The head unit has the last word.** Slots are a preference. A unit with a
spare position may promote the first `overflow` entry onto the main row, so
a button you placed in overflow can still appear beside play/pause.
* **Fewer buttons, cleaner row.** If you want just
`jump-back │ play/pause │ jump-forward`, leave the rest out of the layout
entirely — they keep working from the steering wheel and headset regardless.
## Testing
Test in a real car, or in Google's **Desktop Head Unit (DHU)** emulator:
Install the DHU from the SDK Manager, turn on developer mode and the head unit server in the phone's Android Auto app, then connect: Google's [Test Android Auto apps with DHU](https://developer.android.com/training/cars/testing/dhu) has the steps. Your app appears under the media apps — browse the tree, exercise voice search, and verify artwork, grid/list styles, and section headers.
## Reference
See the [example app](https://github.com/radio-garden/react-native-audio-browser/tree/next/apps/example-native/android) for a complete working manifest and descriptor.
---
---
url: https://audiobrowser.dev/guide/carplay.md
description: >-
CarPlay for audio apps: browse templates generated from your browse tree, the
UIScene and headless React Native host setup, and Siri voice search via
INPlayMediaIntent.
---
# CarPlay
## Overview
CarPlay integration for audio apps works through two systems:
1. **Browse templates** — Tab-based navigation generated from the **browse tree** you declare with `configureBrowser`, handled automatically by the library. If you haven't set that up yet, see [Basic Usage](/guide/basic-usage) for tabs, routes, and sources — this page assumes it's already configured. Every config key used below is documented in [`BrowserConfiguration`](/api/types/browser/#browserconfiguration).
2. **Siri voice search** — The search button on CarPlay launches Siri, which creates an `INPlayMediaIntent`. The library resolves it through the same [`search`](/guide/search) source that powers your in-app search, then queues and plays the results. This requires additional setup in your app (see [Siri Voice Search](#siri-voice-search) below).
On CarPlay's audio interface the search button always triggers Siri — audio apps don't use `CPSearchTemplate` (that's a navigation-app API).
The two systems are independent, but **both** require the [React Native host setup](#react-native-host-uiscene-headless) (UIScene lifecycle + headless RN boot). Every CarPlay app needs it, even browse-only. Siri then adds its own entitlement, Info.plist keys, and intent handler on top.
The **Now Playing Buttons**, **Playing Indicator**, **Loading States** and **Album Line Navigation** sections are optional polish. Skip them to get a minimal integration working.
::: info Before you start
This page assumes you've installed the library and have the player running: add `react-native-audio-browser`, run `pod install` in `ios/`, and call `setupPlayer()` + `configureBrowser()` at startup. See [Getting Started](/guide/getting-started) and [Basic Usage](/guide/basic-usage) first.
:::
## Setup
### Entitlement
Your app needs the CarPlay audio entitlement in your `.entitlements` file:
```xml
com.apple.developer.carplay-audio
```
If your target has no `.entitlements` file yet, add one via Xcode (**Signing & Capabilities → + Capability**) and make sure the target's **`CODE_SIGN_ENTITLEMENTS`** build setting points at it — otherwise the key is ignored at build time.
The CarPlay audio entitlement also must be **granted by Apple** via the [CarPlay entitlement request](https://developer.apple.com/contact/carplay/) before it works on a device — approval can take a while, so request it early. You can still develop against the [CarPlay Simulator](#testing) meanwhile.
### Scene manifest (Info.plist)
Your scene manifest needs **two** scene configurations: the CarPlay template scene (driven by the library's `RNABCarPlaySceneDelegate`) and your phone window scene (driven by your own `PhoneSceneDelegate`, shown in the host setup below). If your app isn't scene-based yet, this whole `UIApplicationSceneManifest` is new:
```xml
UIApplicationSceneManifest
UIApplicationSupportsMultipleScenes
UISceneConfigurations
CPTemplateApplicationSceneSessionRoleApplication
UISceneConfigurationName
CarPlay
UISceneDelegateClassName
RNABCarPlaySceneDelegate
UIWindowSceneSessionRoleApplication
UISceneConfigurationName
Phone
UISceneDelegateClassName
$(PRODUCT_MODULE_NAME).PhoneSceneDelegate
```
The two `UISceneDelegateClassName` strings name the delegate for each scene:
* `RNABCarPlaySceneDelegate` ships with the library. You never implement it; it links in once the `AudioBrowser` pod is installed.
* `PhoneSceneDelegate` is your own, written in the host setup below.
These manifest strings are only a fallback: once you add `configurationForConnecting` (next section), your code picks each scene's delegate. Until you finish the host setup, `PhoneSceneDelegate` does not resolve yet, and that is expected.
## React Native host (UIScene + headless)
This section is **required for any CarPlay integration**, browse-only or Siri. Set it up once; both the browse templates and Siri depend on it.
CarPlay connects through scenes and can launch your app in the background with no phone window. So React Native has to start both on the foreground path (your phone scene) and headless (in a hidden window).
::: warning Two prerequisites
**UIScene lifecycle** — CarPlay requires a `UIWindowSceneDelegate` for the phone window. If your app still sets up its window directly in `AppDelegate`, migrate to scenes first (the sections below build all the pieces).
**New Architecture host, Swift** — these snippets assume a Swift `AppDelegate` built on `RCTReactNativeFactory` and `RCTDefaultReactNativeFactoryDelegate`, which React Native ships from **0.78**.
On React Native versions before 0.78 (see [Getting Started](/guide/getting-started#installation) for the minimum), the template's `AppDelegate` subclasses `RCTAppDelegate` instead, so adapt the same pieces (scene routing, the headless helper, the started flag) to that host.
If yours is still Objective-C (`.mm`), migrating it to Swift first is simpler than translating this wiring by hand. Scaffold a throwaway app (`npx @react-native-community/cli init Tmp`) and use its `AppDelegate.swift` as a reference. ObjC works too (the bridging header is then unnecessary, see [Siri step 3](#_3-bridging-header-swift-appdelegate-only)) but isn't shown here.
:::
### The factory
These AppDelegate snippets need the New-Architecture React host imports:
```swift
import UIKit
import Intents
import React
import React_RCTAppDelegate
import ReactAppDependencyProvider
```
Create the `RCTReactNativeFactory` in `didFinishLaunchingWithOptions`, but **don't** start RN there — the phone scene starts it on the foreground path, and the headless helper starts it on the background path:
```swift
var reactNativeFactory: RCTReactNativeFactory?
private var reactNativeDelegate: ReactNativeDelegate?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
let delegate = ReactNativeDelegate()
delegate.dependencyProvider = RCTAppDependencyProvider()
reactNativeDelegate = delegate
reactNativeFactory = RCTReactNativeFactory(delegate: delegate)
// Note: do NOT start RN here — the scene delegates own startup.
return true
}
```
`ReactNativeDelegate` is a `RCTDefaultReactNativeFactoryDelegate` subclass **you** define (standard New-Architecture AppDelegate boilerplate — it supplies your JS bundle URL); `RCTAppDependencyProvider` is a React-core class. Neither comes from this library. The default New-Arch template generates both — if you scaffolded with it you already have them; otherwise this is the whole subclass:
```swift
class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate {
override func sourceURL(for bridge: RCTBridge) -> URL? { bundleURL() }
override func bundleURL() -> URL? {
#if DEBUG
RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
}
}
```
### The headless helper
Two things call this helper, which is why it's required even for **browse-only** apps:
* The library's `RNABCarPlaySceneDelegate` calls `startReactNativeHeadless` on your `AppDelegate` every time CarPlay connects. So a browse-only CarPlay launch boots RN automatically. When the phone scene already started RN, the helper's guard makes the call a no-op.
* Your Siri intent handler calls it (step 4) for a background intent launch.
::: warning Declare it `@objc func startReactNativeHeadless()`
The library finds this method **by Objective-C selector**. It must be named exactly `startReactNativeHeadless`, take no arguments, and be marked `@objc`: Swift does not expose a plain method to the Objective-C runtime. Otherwise the library's CarPlay delegate can't boot RN and browse screens hang empty.
:::
```swift
// Properties on your AppDelegate.
private var reactNativeStarted = false
private var headlessWindow: UIWindow?
/// Boots React Native into a hidden window when no UI scene exists yet.
/// Called by the library's CarPlay delegate (browse) and your Siri handler.
/// Safe to call repeatedly — it starts RN at most once.
@objc func startReactNativeHeadless() {
guard !reactNativeStarted else { return }
reactNativeStarted = true
// RCTReactNativeFactory needs a window to host the root view.
headlessWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
headlessWindow?.isHidden = true
// `startReactNative(withModuleName:in:launchOptions:)` is a React-core method
// on RCTReactNativeFactory — not a library API. "YourAppModuleName" is your
// app.json `name` (= the AppRegistry.registerComponent string); the phone
// scene and this headless path must use that same name.
reactNativeFactory?.startReactNative(
// ⚠️ replace with your app.json `name`
withModuleName: "YourAppModuleName",
in: headlessWindow,
launchOptions: nil
)
}
/// Called by the phone scene when it starts RN on the foreground path, so the
/// headless helper doesn't start it again. Only the headless helper checks
/// `reactNativeStarted`: the phone scene always starts RN in its own window.
func markReactNativeStarted() {
reactNativeStarted = true
}
```
### The phone scene delegate
Create this as a **new `.swift` file in your app target** (e.g. `PhoneSceneDelegate.swift`, next to `AppDelegate.swift`). It must compile into your app's own module — that's why the Info.plist refers to it as `$(PRODUCT_MODULE_NAME).PhoneSceneDelegate`. It starts RN on the foreground path and flips the shared flag via `markReactNativeStarted()`:
```swift
class PhoneSceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(
_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions
) {
guard session.role == .windowApplication,
let appDelegate = UIApplication.shared.delegate as? AppDelegate,
let windowScene = scene as? UIWindowScene else { return }
let window = UIWindow(windowScene: windowScene)
appDelegate.window = window
appDelegate.markReactNativeStarted() // foreground path owns RN startup
// Module name must exactly match the headless helper / registerComponent.
appDelegate.reactNativeFactory?.startReactNative(
// ⚠️ replace with your app.json `name`
withModuleName: "YourAppModuleName",
in: window,
launchOptions: nil
)
self.window = window
}
}
```
::: info After a headless launch
The phone scene starts RN even when CarPlay or Siri already started it headless. The factory reuses its React host, so JS keeps running in the same runtime.
But your root component mounts a second time, in the phone window, while the headless one stays mounted in the hidden window. Keep app-wide side effects (player setup, `configureBrowser`) idempotent, or put them outside the root component.
:::
See the example app's [`AppDelegate.swift`](https://github.com/radio-garden/react-native-audio-browser/blob/next/apps/example-native/ios/AudioBrowserExample/AppDelegate.swift) and [`PhoneSceneDelegate.swift`](https://github.com/radio-garden/react-native-audio-browser/blob/next/apps/example-native/ios/AudioBrowserExample/PhoneSceneDelegate.swift) for the complete, copy-pasteable versions.
### Routing scene connections
Now that both delegates exist, route each incoming scene to the right one from your `AppDelegate` — the library's `RNABCarPlaySceneDelegate` for CarPlay, your `PhoneSceneDelegate` for the phone window:
```swift
func application(
_ application: UIApplication,
configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions
) -> UISceneConfiguration {
if connectingSceneSession.role == UISceneSession.Role.carTemplateApplication {
let config = UISceneConfiguration(
name: "CarPlay", sessionRole: connectingSceneSession.role)
// RNABCarPlaySceneDelegate is an ObjC class the library ships, so it's
// resolved by name rather than imported.
config.delegateClass =
NSClassFromString("RNABCarPlaySceneDelegate") as? UIResponder.Type
return config
}
// Phone scene — your own delegate, defined above.
let config = UISceneConfiguration(
name: "Phone", sessionRole: connectingSceneSession.role)
config.delegateClass = PhoneSceneDelegate.self
return config
}
```
As noted in the scene manifest above, the `delegateClass` you set here is what actually routes each scene; the Info.plist names are just the fallback. Seeing each delegate in both places is expected.
One coupling that **is** load-bearing: the `name:` you pass to `UISceneConfiguration` (`"CarPlay"` / `"Phone"`) must match a `UISceneConfigurationName` in the manifest. Rename one without the other and iOS crashes at connect time with *"no UISceneConfiguration named …"*.
### The assembled `AppDelegate`
The fragments above all live on one `AppDelegate`. Here is the whole class in one piece, to copy.
It **replaces** the `@main class AppDelegate` your RN template generated in `ios//AppDelegate.swift` (you keep one `@main`; don't add a second). The Siri `handlerFor` method at the end is needed only if you add [Siri Voice Search](#siri-voice-search):
```swift
import UIKit
import Intents
import React
import React_RCTAppDelegate
import ReactAppDependencyProvider
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var reactNativeFactory: RCTReactNativeFactory?
private var reactNativeDelegate: ReactNativeDelegate?
private var reactNativeStarted = false
private var headlessWindow: UIWindow?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
let delegate = ReactNativeDelegate()
delegate.dependencyProvider = RCTAppDependencyProvider()
reactNativeDelegate = delegate
reactNativeFactory = RCTReactNativeFactory(delegate: delegate)
return true // don't start RN here — the scene delegates own startup
}
// Route each connecting scene to its delegate.
func application(
_ application: UIApplication,
configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions
) -> UISceneConfiguration {
if connectingSceneSession.role
== UISceneSession.Role.carTemplateApplication {
let config = UISceneConfiguration(
name: "CarPlay", sessionRole: connectingSceneSession.role)
config.delegateClass =
NSClassFromString("RNABCarPlaySceneDelegate") as? UIResponder.Type
return config
}
let config = UISceneConfiguration(
name: "Phone", sessionRole: connectingSceneSession.role)
config.delegateClass = PhoneSceneDelegate.self
return config
}
// Boots RN into a hidden window when there's no UI scene (background launch).
// `@objc` so the library's CarPlay delegate can find it by selector.
@objc func startReactNativeHeadless() {
guard !reactNativeStarted else { return }
reactNativeStarted = true
headlessWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
headlessWindow?.isHidden = true
reactNativeFactory?.startReactNative(
// ⚠️ replace with your app.json `name`
withModuleName: "YourAppModuleName",
in: headlessWindow,
launchOptions: nil
)
}
// Called by PhoneSceneDelegate so the headless path won't double-start RN.
func markReactNativeStarted() { reactNativeStarted = true }
// Siri only — needed when you add Siri Voice Search (step 4). Requires the
// bridging header so `RNABAudioBrowser` is visible in Swift.
func application(
_ application: UIApplication,
handlerFor intent: INIntent
) -> Any? {
startReactNativeHeadless()
return RNABAudioBrowser.handler(for: intent)
}
}
// Same file as AppDelegate. Standard New-Arch host delegate —
// supplies the bundle URL.
class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate {
override func sourceURL(for bridge: RCTBridge) -> URL? { bundleURL() }
override func bundleURL() -> URL? {
#if DEBUG
RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
}
}
```
This is the complete `AppDelegate.swift` (the `@main class AppDelegate` plus its `ReactNativeDelegate` in the same file). `PhoneSceneDelegate` lives in its **own** `PhoneSceneDelegate.swift` (shown above). Those two files are the complete native side.
::: warning Don't blindly overwrite an AppDelegate you've customized
This block is the minimal shape. If your existing `AppDelegate` / `ReactNativeDelegate` already has extra overrides (bundle customization, linking setup, push/deep-link handlers, `customize(rootView:)`, extra modules), **keep them**.
Merge the CarPlay additions into your file rather than replacing it wholesale: the factory split, `configurationForConnecting`, the headless helper, `markReactNativeStarted`, and the Siri `handlerFor`.
:::
### Where to call `configureBrowser`
Call `configureBrowser` (and `setupPlayer`) as a **top-level side-effect in `index.js`**, next to `AppRegistry.registerComponent`. It then runs when the JS bundle loads, mounted UI or not.
The headless helper mounts your root component in the hidden window, and the phone scene mounts it again later. So a call in a component's `useEffect` runs once per window, and only after the first render. That's late for Siri, whose handler waits only briefly for setup (see [step 4](#_4-appdelegate-intent-handler)). A top-level call in `index.js` runs once, as soon as the bundle loads.
`configureBrowser` **replaces** the whole config each time; it doesn't merge. So build one object with everything together: tabs, routes, and (for Siri) search. The snippets further down show one key at a time for brevity.
```ts
const browserConfig = {
// Tabs along the top of the CarPlay browser (see the tab limit in
// /guide/browser#tabs-and-the-initial-path).
tabs: [{ title: 'Home', path: '/' }],
// routes: path → BrowserSource (static page, callback, or HTTP).
routes: {
'/': async () => ({
path: '/',
title: 'Home',
children: [{ title: 'Crunchy Greens FM', src: 'https://...' }]
})
},
// search: required for Siri voice search (omit for browse-only).
search: { baseUrl: 'https://api.example.com/search' }
}
```
Then apply it as a top-level side-effect in `index.js`:
```js
// index.js
import { AppRegistry } from 'react-native'
import { configureBrowser, setupPlayer } from 'react-native-audio-browser'
import App from './App'
import { name as appName } from './app.json'
import { browserConfig } from './browserConfig' // the object above
AppRegistry.registerComponent(appName, () => App)
// Runs on every launch — including headless CarPlay / Siri — because it's a
// module side-effect, not tied to a mounted component.
void (async () => {
await setupPlayer()
configureBrowser(browserConfig)
})()
```
The `"YourAppModuleName"` in the Swift snippets above is exactly this `appName` — your `app.json` `name`, identical to the string passed to `AppRegistry.registerComponent` (the same in the default RN template). The headless helper and the phone scene must both start RN with that name.
## Siri Voice Search
Siri voice search builds on the [React Native host setup](#react-native-host-uiscene-headless) above — make sure that's in place first. Then complete the steps below, in order:
* **Step 0 — configure a `search` source** (the warning box just below; required, easy to forget)
* **Steps 1–4** — Siri entitlement, Info.plist keys, bridging header, intent handler
::: warning Step 0 (required) — a configured `search` source
Siri voice search resolves spoken queries through the **same [`search`](/guide/search) source as your in-app search**. Without one, "play jazz" returns **nothing**, even with steps 1–4 wired up. Add `search` to the one config you pass to [`configureBrowser`](#where-to-call-configurebrowser) at startup:
```ts
configureBrowser({
// …your tabs / routes …
search: {
// GET https://api.example.com/search?q=jazz — the library appends
// `q` plus structured voice params (`mode`, `genre`, `artist`,
// `album`, `reference`) and expects a bare Track[] back (a JSON
// array, not a page object), where each playable Track needs at
// least `title` + `src`.
baseUrl: 'https://api.example.com/search'
}
})
```
The browse templates work without `search`; Siri does not. See [Search](/guide/search#configuring-search) for:
* the full `SearchParams` (genre / artist / album / `mode` / `reference`)
* the callback form, which returns [`Track`](/api/types/browser-nodes/#track)`[]` itself and receives the spoken text as `query` rather than `q`
* `transform`, for rewriting requests
:::
CarPlay's tab bar already has a **search button that launches Siri**, which works once the steps below are wired up.
The library can also show an **"Ask Siri to Play Audio" cell inside a list** as an extra entry point. This is optional polish, not what enables Siri search. To add it, set [`carPlaySiriListButton`](/api/types/browser/#carplaysirilistbuttonposition) on the resolved content your route source returns:
```ts
configureBrowser({
// `routes` maps a path → a `BrowserSource`: a static page object, an async
// callback returning one (as here), or an HTTP request config. See
// Basic Usage and the BrowserSource type: /api/types/browser/#browsersource
routes: {
'/': async () => ({
path: '/',
title: 'Home',
carPlaySiriListButton: 'top',
children: [{ title: 'Crunchy Greens FM', src: 'https://...' }]
})
}
})
```
(Tabs themselves come from your separate [`tabs`](/api/types/browser/#tabs) config, not from this route — the `'/'` route here is just where the button is attached. See [Basic Usage](/guide/basic-usage) for how `tabs` and `routes` fit together.)
The `carPlaySiriListButton` property accepts `'top'` or `'bottom'` to control where the system assistant cell appears. It only affects CarPlay, not the phone UI.
To complete the setup, your app needs the Siri entitlement, a couple of Info.plist keys, a bridging header, and a one-line handler in your AppDelegate. Media intents are handled in-app: Siri delivers the `INPlayMediaIntent` straight to your `AppDelegate`.
::: info iOS version
The version numbers on this page are capability notes within the library's [iOS floor](/guide/getting-started#installation):
* The in-app handler API (`application(_:handlerFor:)`) exists from iOS 14, so you never need to gate on it.
* The automatic CarPlay loading spinner needs iOS 18.4+.
:::
### 1. Siri entitlement
Add the Siri entitlement to the **same `.entitlements` file** as the CarPlay key — both live in one ``:
```xml
com.apple.developer.carplay-audio
com.apple.developer.siri
```
The reliable way to add this is Xcode → **Signing & Capabilities → + Capability → Siri**, which writes the key and enables **SiriKit on your App ID** (via automatic signing or the developer portal). Unlike the CarPlay audio entitlement, Siri does **not** require a manual Apple approval request — enabling the capability is enough.
### 2. Siri Info.plist keys
Add Siri usage description and supported media categories to your app's Info.plist:
```xml
NSSiriUsageDescription
Siri is used for voice-controlled media playback via CarPlay.
INIntentsSupported
INPlayMediaIntent
INUpdateMediaAffinityIntent
INAddMediaIntent
INSupportedMediaCategories
INMediaCategoryRadio
```
`INIntentsSupported` registers the intents your app can handle. The library's handler vends a handler for three intents:
* **`INPlayMediaIntent`** — search / resume / play (the core voice-search flow).
* **`INUpdateMediaAffinityIntent`** — "like" / "dislike" the current track.
* **`INAddMediaIntent`** — add the current track to favorites.
Register only the ones you want; `INPlayMediaIntent` alone is enough for voice search. The [`INSupportedMediaCategories`](https://developer.apple.com/documentation/bundleresources/information-property-list/insupportedmediacategories) values tell Siri which spoken requests to route to your app — if they don't cover your content, Siri may hand the request to a **different app**, so list every category you actually support.
### 3. Bridging Header (Swift AppDelegate only)
The intent API lives in the library's CocoaPod, **`AudioBrowser`** (the umbrella header for the `react-native-audio-browser` package). An **Objective-C** AppDelegate just `#import ` directly and skips this step.
A **Swift** AppDelegate reaches it through a bridging header. If your app already has one (check `SWIFT_OBJC_BRIDGING_HEADER`), add the import to it; otherwise create one and point that build setting at it:
**YourApp-Bridging-Header.h:**
```objc
#import
```
::: tip If the import won't resolve
`` resolves only once the `AudioBrowser` pod is linked. Run `pod install` (from `ios/`) after adding the npm dependency, and confirm the pod is named **`AudioBrowser`** in your `Podfile.lock`. A "module 'AudioBrowser' not found" error almost always means `pod install` hasn't run.
:::
### 4. AppDelegate intent handler
For in-app intent handling, implement `application(_:handlerFor:)` on your `AppDelegate`, boot RN headless (the [`startReactNativeHeadless()`](#the-headless-helper) helper from the host setup), and return the library's handler object. This is the same method already shown (commented "Siri only") in the [assembled `AppDelegate`](#the-assembled-appdelegate) — add it once, not twice; it's repeated here in isolation:
```swift
import Intents
func application(
_ application: UIApplication,
handlerFor intent: INIntent
) -> Any? {
// The intent may have cold-launched us with no scene — boot RN first;
// the library's handler waits for RN before resolving.
startReactNativeHeadless()
return RNABAudioBrowser.handler(for: intent)
}
```
`RNABAudioBrowser.handler(for:)` is the library's **only** intent entry point, with no separate registration or setup call. It returns an opaque handler object for the intents it supports (`INPlayMediaIntent`, `INUpdateMediaAffinityIntent`, `INAddMediaIntent`) and `nil` for anything else.
The library resolves the spoken query through your configured [`search`](/guide/search) source (the same one your in-app search uses — it is **not** a browse route), queues the results, and starts playback automatically.
::: tip The handler waits only briefly for setup
On a cold launch, the handler waits up to about **8 seconds** for your JS to run `setupPlayer()` and `configureBrowser()`, then fails the intent. So call both at the top level of `index.js`, before any slow async work (see [Where to call `configureBrowser`](#where-to-call-configurebrowser)).
That limit covers only the wait for setup. Your Gate's resolver and your `search` source run after it with no time limit of their own, so keep them quick: Siri gives up on a slow request.
If you use a [Gate](/guide/gate), a paywall or region check, it can refuse the search. It blocks search and browsing from the car, not playback, so "resume" still plays.
:::
> **Why a handler object, not `application(_:handle:completionHandler:)`?** The latter is not a real `UIApplicationDelegate` method, so iOS never calls it. With no in-app handler registered, the system falls back to a `UISIntentForwardingAction`, which crashes in `-[INHandleIntentForwardingActionResponse isSuccess]`.
>
> Returning a handler from `application(_:handlerFor:)` keeps iOS on the in-app path. **No separate Intents Extension is required**; everything runs in-app.
### How It Works
1. User taps the search button on a CarPlay tab
2. Siri activates and listens for a voice query
3. iOS creates an `INPlayMediaIntent` carrying the parsed query
4. The system asks your app for a handler via `application(_:handlerFor:)` and drives the intent against it
5. The library resolves the request and starts playback — **resuming** the last session when the user just said your app's name, otherwise **searching** your content (genre/artist/album/etc. are forwarded as structured search params)
6. CarPlay's Now Playing screen updates automatically
## Now Playing Buttons
The Now Playing screen always has CarPlay's transport controls. More buttons, one of each kind in the table below, go in the row beneath them: list them in `ios.carPlayNowPlayingButtons`, left to right in the order you want them:
```ts
await setupPlayer({
capabilities: { favorite: true },
ios: {
carPlayNowPlayingButtons: ['shuffle', 'repeat', 'favorite', 'playback-rate']
}
})
```
You can also change them later with `updateOptions({ ios: { carPlayNowPlayingButtons: [...] } })`. The default is `[]`, which means no extra buttons.
| Button | What a tap does |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `'shuffle'` | Turns shuffle on or off. |
| `'repeat'` | Cycles the repeat mode: off → track → queue → off. |
| `'favorite'` | Toggles the playing track's favorite state; the heart is filled while it is a favorite. See [Favorites](/guide/favorites). |
| `'playback-rate'` | Steps to the next rate in `ios.playbackRates`, wrapping from the last back to the first. With `playbackRates: []` the tap does nothing. |
* **Each button is drawn once.** A button listed twice keeps its first position.
* **More than five entries log a warning.** Five is CarPlay's limit for the row; the count includes repeats.
* **A [gate](/guide/gate) hides them.** While a gate is active the row is empty. The transport controls stay.
The **Up Next** button is separate. It opens the queue and shows only when the queue has more than one track. Set `ios.carPlayUpNextButton: false` to never show it.
## Playing Indicator
CarPlay marks the playing item in browse lists with a now-playing indicator. `ios.carPlayPlayingIndicatorLocation` chooses where it draws:
* `'leading'` (default): in the artwork slot, in place of the row's artwork while it plays, as Apple Music does.
* `'trailing'`: at the end of the row, so the artwork stays visible.
If you change it with `updateOptions`, rows already on screen update too.
## Loading States
Browse screens show a loading state while their content resolves — pushed destinations, tabs loading lazily, and the startup screen while tabs are queried. On iOS 18.4+ the system loading spinner is shown automatically. Older iOS versions have no spinner API; those screens stay blank unless you supply a [`carPlayLoadingTitle`](/api/types/browser/#carplayloadingtitle):
```ts
configureBrowser({
carPlayLoadingTitle: t('loading')
// ...
})
```
The title renders as the list's centered empty state and disappears as soon as content arrives.
## Album Line Navigation
The album line on the Now Playing screen can navigate into the browse tree. It becomes tappable when the active track has both:
* an **`album`** string, which CarPlay builds the tappable line from (see the warning below)
* an **`albumPath`**: a `path` in your [`routes`](/guide/basic-usage), so the destination must exist there
Tapping the line pushes that path:
```ts
{
title: 'Sweet Pea',
artist: 'The Radishes',
album: 'Greens',
src: 'https://…',
albumPath: '/album/greens'
}
```
For tracks without an `albumPath`, configure a [`resolveAlbumPath`](/api/types/browser/#resolvealbumpath) resolver. It runs when the active track changes (not at tap time), so the album line only becomes tappable when there is actually somewhere to go:
```ts
configureBrowser({
// `slugify` here is your own helper (illustrative) — turn an album name
// into a browse path that exists in your `routes`.
resolveAlbumPath: (track) =>
track.album ? `/album/${slugify(track.album)}` : undefined
// ...
})
```
Return a browse path to enable the album line for that track, or `undefined` to leave it untappable.
::: warning Album metadata required
CarPlay renders the tappable album/artist button as a **separate line built from the track's `album`**: the third metadata line, with a chevron. A track without an `album` gives CarPlay no string to turn into a button, and the artist line alone is never tappable.
Set `album` on any track that should offer album-line navigation. See [Now Playing](/guide/now-playing) for the full field-by-surface rendering matrix.
:::
## Template Depth
CarPlay limits an audio app's template stack to **five templates, the tab bar included** (see Apple's [CarPlay App Programming Guide](https://developer.apple.com/carplay/)), so the stack is full four pushes in. Now Playing and Up Next each take a slot like any list.
A browse tree with a fixed shape (tabs → show → episodes) never gets there; one that can be drilled without end — a place, a place near it, a place near that — does.
At the limit, the library replaces the **top** page with the new one, so a push always lands:
```
[tabs, A, B, C, D] + push E
[tabs, A, B, C, E]
```
* **Forward never blocks.** A deeper list, Now Playing and Up Next all open at full depth.
* **Back skips one page.** From `E` it goes to `C`: `D`, the page the listener came from, is the one that was replaced. Below full depth, back works as usual.
* **The swap is a pop and a push.** CarPlay can't replace a template in place, so the library pops the top one without animation and then pushes the new one.
Each replacement is logged under the `com.audiobrowser` subsystem, category `TemplateStack`:
```
push at the depth limit: replacing the top, CPListTemplate, with CPListTemplate
```
To watch for it on the simulator:
```sh
xcrun simctl spawn booted log stream --level info \
--predicate 'subsystem == "com.audiobrowser" AND category == "TemplateStack"'
```
An `error` line in that category means the pop or the push failed; it names the template involved.
## Testing
Test your app in the `CarPlay Simulator.app`, which is part of the [Additional Tools for Xcode](https://developer.apple.com/download/all/?q=additional%20tools%20for%20xcode). Siri voice search works there, so you can exercise the full intent flow without a car.
CarPlay support on the iOS Simulator can be a little flaky. If something looks broken, retry, or check on a physical device.
### Troubleshooting
| Symptom | Likely cause |
| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| Siri mic opens but returns nothing | No [`search` source](#siri-voice-search) configured (Step 0). |
| The "Ask Siri" cell does nothing | Siri entitlement / Info.plist keys / intent handler not wired (steps 1–4). |
| CarPlay browse screens hang empty | `startReactNativeHeadless` missing, misnamed or missing `@objc`: the library calls it by selector. |
| Build error: *module 'AudioBrowser' not found* | `pod install` hasn't linked the `AudioBrowser` pod. |
| Crash: *no UISceneConfiguration named …* | The `name:` in `configurationForConnecting` doesn't match `UISceneConfigurationName` in the manifest. |
## Reference
See the [example app](https://github.com/radio-garden/react-native-audio-browser/tree/next/apps/example-native/ios/AudioBrowserExample) for a complete working implementation.
---
---
url: https://audiobrowser.dev/guide/native-callback-fetch.md
description: >-
Why React Native's fetch hangs inside the callbacks you pass to
configureBrowser, such as browse route callbacks and search sources, when the
device is asleep, and what to use instead.
---
# Networking in native callbacks (don't use `fetch`)
**Does a callback you pass to `configureBrowser` network with React Native's
built-in `fetch`, and work in your app but *hang* when the device is asleep?
Browsing on CarPlay or Android Auto with the screen off, or answering a voice
intent, are typical cases. Then you are in the right place.**
The browse screen goes blank because the request never resolves. The fix is to
fetch with
[`react-native-nitro-fetch`](https://github.com/margelo/react-native-nitro-fetch),
or to let the library do the request natively.
## The problem
The library invokes the async callbacks you provide **from native code**,
whenever the system asks for content — including while your app is asleep:
* browse **route callbacks** (`configureBrowser({ routes })`),
* the **search source** (`configureBrowser({ search })`),
* request **`transform`** callbacks,
* `media` and `artwork` **`resolve`** callbacks,
* **config resolvers**, such as `request: async () => …`,
* a **`tabs`** callback.
A locked iPhone browsing your library on CarPlay, or a "play jazz" voice command
with the screen dark, runs these callbacks with the app backgrounded. The first
native call into JS runs fine — but the moment your callback `await`s a `fetch`,
it hangs until the phone wakes.
### Why `fetch` hangs while asleep
As of React Native 0.88, its `fetch` is the [`whatwg-fetch`](https://github.com/JakeChampion/fetch)
polyfill, which resolves its promise with a **zero-delay timer**, not a
microtask:
```js
// inside whatwg-fetch
setTimeout(function () {
resolve(new Response(body, options))
}, 0)
```
While the app is in the background, JS timers don't fire reliably
([RN #54534](https://github.com/react/react-native/issues/54534)). Native
networking (`RCTNetworking`) **does** receive the response, but the
`setTimeout(0)` that hands it to your `await` doesn't run. The promise hangs
until the screen wakes, and the browse list spins or shows blank.
On Android, React Native's timer manager stops firing JS timers once the host
activity pauses, unless a headless JS task is running. An app backgrounded
behind Android Auto therefore shows the same symptom, and the same fix applies.
This isn't specific to this library: it affects any `fetch` on a sleeping
device.
## The fix: `react-native-nitro-fetch`
[`react-native-nitro-fetch`](https://github.com/margelo/react-native-nitro-fetch)
is a drop-in `fetch` replacement that runs the request natively and resolves
its promise without a JS timer: no `setTimeout`, no `whatwg-fetch`.
It therefore completes even when the callback runs while the device is asleep.
This library is already a Nitro module, so it's a natural fit.
```bash
npm install react-native-nitro-fetch react-native-nitro-modules
```
You already have `react-native-nitro-modules` (it's a peer dependency of this
library); you'll need a native rebuild (`pod install` + rebuild) after
installing.
Then add one import at the top of any module with a native-invoked callback — it
shadows the global `fetch`, so the call sites don't change:
```ts
import { configureBrowser } from 'react-native-audio-browser'
import { fetch } from 'react-native-nitro-fetch'
configureBrowser({
tabs: [{ title: 'Browse', path: '/browse' }],
routes: {
'/browse': async ({ path }) => {
const res = await fetch('https://api.example.com/browse')
const { children } = await res.json()
return { path: path, title: 'Browse', children }
}
}
})
```
Do the same in every module that holds a callback from the list above, not only
routes.
## Even simpler: let the library fetch natively
If a route just maps a path to an HTTP request, you don't have to write a JS
callback at all. Give the browse source a `baseUrl` and the **library performs
the request natively** for each navigated path — no JS networking, nothing to
stall:
```ts
configureBrowser({
// Each browse path is fetched over HTTP on the native side.
browse: { baseUrl: 'https://api.example.com' },
tabs: [{ title: 'Browse', path: '/browse' }]
})
```
The navigated path is appended to `baseUrl`. To remap or shape the request, use
a [`transform`](/guide/browser#shaping-requests). The request itself stays
native, so a transform that does no networking of its own is safe.
The search source accepts the same request-config form, so it can be served
natively too. Reach for `react-native-nitro-fetch` only when you need logic a
request config can't express (combining sources, reading local storage, custom
shaping).
## When it's safe to use plain `fetch`
This only affects code the library invokes from native while the app is asleep.
Networking driven by **your own app UI in the foreground** — a screen the user is
looking at — runs on the normal JS loop and is unaffected; plain `fetch` is fine
there.
Rule of thumb: if the OS can run the code with the screen off, don't
depend on `fetch`.
## Further reading
* [`react-native-nitro-fetch`](https://github.com/margelo/react-native-nitro-fetch)
* [JS timers don't fire when the app is backgrounded (RN #38711, closed in 2023)](https://github.com/react/react-native/issues/38711)
* [Timers & fetch freeze behind a native activity (RN #54534)](https://github.com/react/react-native/issues/54534)
---
---
url: https://audiobrowser.dev/guide/android-certificates.md
description: >-
Why Android playback fails with SSLHandshakeException / "Trust anchor for
certification path not found" on HTTPS streams whose server omits its
intermediate certificate, and what the AIA toolkit does and does not reach.
---
# Android: missing intermediate certificates
Android playback of an HTTPS stream can fail with `SSLHandshakeException`,
`CertPathValidatorException` or "Trust anchor for certification path not found"
while the same stream plays on iOS and in a desktop browser. The cause is almost
always a server that omits an intermediate certificate.
The library ships `AiaTls`, a toolkit that fetches the missing certificate from
the URL in the leaf's Authority Information Access (AIA) extension. It does not
reach playback (see [The problem](#the-problem)), so installing `AiaTls` does
not fix a failing stream.
The reliable fix is for the server to send its full chain. The client-side
alternative is a Network Security Config that trusts the missing intermediate (see
[Fix playback from the app](#fix-playback-from-the-app)). This guide shows how
to confirm the diagnosis, and where `AiaTls` does apply.
## The problem
Some HTTPS servers are misconfigured to send only their **leaf** certificate and
omit the **intermediate** certificate(s) needed to chain up to a trusted root. A
correctly configured server sends the full chain; a misconfigured one leaves the
client to find the gap on its own.
* **iOS and web browsers** recover automatically: they follow the leaf's
Authority Information Access (AIA) "CA Issuers" pointer to fetch the missing
intermediate. (This is why the stream works everywhere except Android.)
* **Android's default trust manager does not.** It validates only what the server
sent, so playback of such a stream fails with:
```
javax.net.ssl.SSLHandshakeException:
java.security.cert.CertPathValidatorException:
Trust anchor for certification path not found.
```
The player sends media over its own OkHttp client, which validates with the
platform default trust manager. OkHttp does not read the process-wide default
`SSLSocketFactory`, and the library offers no way to give that client another
one.
Nothing the app sets as a socket factory reaches playback. Only a Network
Security Config does, because the platform trust manager reads it.
> **iOS needs no setup.** Apple's TLS stack chases AIA intermediates on its own,
> so there is nothing to configure on iOS — this guide is Android-only.
## Is this actually your problem?
Before you report the stream to its operator or change TLS state, confirm the
failing stream really is a missing-intermediate case. Other TLS failures look
alike: an expired cert, an SNI mismatch, or a genuinely untrusted root.
`AiaTls` addresses none of them.
Run, against your failing stream's **host** — use just the hostname, not the full
stream URL. If your stream URL is `https://example.com:8000/live.mp3`, the host is
`example.com` and the port is `8000` (omit the path); plain `https://` URLs with no
port use `443`:
```sh
openssl s_client -connect example.com:443 \
-servername example.com -showcerts /dev/null |
openssl x509 -noout -ext authorityInfoAccess
```
In the output:
* A **complete** chain lists two or more certificates under
`Certificate chain` (leaf `s:.../CN=host` then one or more issuers `i:...`) and
ends with `Verify return code: 0 (ok)`.
* A **missing-intermediate** server typically shows **only one** certificate in
the chain and a verify error such as
`Verify return code: 21 (unable to verify the first certificate)`.
* A `CA Issuers - URI:` line in the second command's output is the pointer
`AiaTls` follows. One certificate, a verify error and this pointer together
are a missing intermediate. For playback, the server operator has to send
the full chain, or the app trusts the intermediate (see
[Fix playback from the app](#fix-playback-from-the-app)).
`AiaTls` can complete it only for connections your app makes itself:
`HttpURLConnection` through the process default, or an OkHttp client you
build (see [Advanced](#advanced-custom-okhttp-client)).
Prefer a browser? Paste the host into the [SSL Labs server
test](https://www.ssllabs.com/ssltest/) — it flags **"Chain issues: Incomplete"**
for this exact problem — or use [whatsmychaincert.com](https://whatsmychaincert.com/).
> **Want to see a broken chain first?** `incomplete-chain.badssl.com` is a public
> test host that omits its intermediate on purpose. Run both commands above
> against `incomplete-chain.badssl.com:443` to see the signature: one
> certificate, a verify error and a `CA Issuers` pointer.
If the chain is complete, or there is no `CA Issuers` AIA pointer, `AiaTls` will
**not** help — see [Caveats](#caveats).
## Fix playback from the app
The player's OkHttp client validates with the platform default trust manager.
On Android 7 (API 24) and later, that trust manager reads the app's Network
Security Config. So a `` for the stream's host can trust the
missing intermediate, with no change to the library.
1. Download the intermediate from the leaf's `CA Issuers - URI` and save it as
`res/raw/stream_intermediate.crt` (PEM or DER).
2. Add `res/xml/network_security_config.xml`:
```xml
example.com
```
3. Point the `` element of `AndroidManifest.xml` at it with
`android:networkSecurityConfig="@xml/network_security_config"`.
The cost is upkeep. The app now bundles that certificate. When the CA rotates
its intermediate or the server changes CA, playback fails again until you ship
an update. Fixing the server's chain has no such cost.
## Opt in
The library ships an **additive** AIA-chasing `SSLSocketFactory` but does **not**
install it for you. Installing it changes process-global TLS state, so that is
the app's decision, not the library's.
::: warning This does not fix playback
The install below covers your app's own `HttpURLConnection` traffic only, not
the player (see [The problem](#the-problem)).
For a stream that fails in the player, fix the server's chain, or trust the intermediate in a Network Security Config (see
[Fix playback from the app](#fix-playback-from-the-app)).
:::
To enable it, set it as the default in the `onCreate` of your **existing**
`MainApplication`. `MainApplication.onCreate` runs before React Native loads your
JS bundle, so no connection can have started yet.
> Add the highlighted line to the `MainApplication` you already have (it lives at
> `android/app/src/main/java/.../MainApplication.kt` or `.java`). **Don't create a
> new file or a second `MainApplication` class** — just drop the call into the
> `onCreate` you already have, after `super.onCreate()`.
::: code-group
```kotlin [MainApplication.kt]
import com.audiobrowser.tls.AiaTls
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLSocketFactory
import android.util.Log
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
try {
val aiaFactory = AiaTls.socketFactory() // [!code ++]
HttpsURLConnection.setDefaultSSLSocketFactory(aiaFactory) // [!code ++]
installedSslFactory = aiaFactory // [!code ++]
} catch (e: Exception) {
// Never let TLS setup block startup; connections keep default behaviour.
Log.w("MainApplication", "Failed to install AIA-chasing TLS", e)
}
// ... the rest of your existing setup
}
companion object {
/** Kept so you can confirm the install — see "Verify it worked". */
var installedSslFactory: SSLSocketFactory? = null
}
}
```
```java [MainApplication.java]
import com.audiobrowser.tls.AiaTls;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import android.util.Log;
public class MainApplication extends Application {
/** Kept so you can confirm the install — see "Verify it worked". */
public static SSLSocketFactory installedSslFactory = null;
@Override
public void onCreate() {
super.onCreate();
try {
SSLSocketFactory aiaFactory = AiaTls.socketFactory(); // [!code ++]
HttpsURLConnection.setDefaultSSLSocketFactory(aiaFactory); // [!code ++]
installedSslFactory = aiaFactory; // [!code ++]
} catch (Exception e) {
// Never let TLS setup block startup; connections keep default behaviour.
Log.w("MainApplication", "Failed to install AIA-chasing TLS", e);
}
// ... the rest of your existing setup
}
}
```
:::
This reaches every `HttpURLConnection` in the process. It does not reach the
player (see [The problem](#the-problem)).
`AiaTls` ships with the `react-native-audio-browser` Android module you already
installed — the `com.audiobrowser.tls` import resolves with no extra Gradle
dependency.
> **Rebuild after adding this.** `AiaTls` is native Kotlin, so a JS-only reload
> won't pick up the new call — do a full native rebuild:
>
> ```sh
> npx react-native run-android
> # if the build seems stale, clear Gradle first:
> cd android && ./gradlew clean && cd .. && npx react-native run-android
> ```
>
> No manifest or permission change is needed — RN apps already hold the `INTERNET`
> permission the AIA fetch uses, and the cleartext fetch is handled for you (see
> [The cleartext fetch is handled for you](#the-cleartext-fetch-is-handled-for-you)).
## The cleartext fetch is handled for you
The stream itself stays on HTTPS. Only the fetch of the *missing intermediate*
uses the leaf's `CA Issuers` URL, and CAs publish that URL over plain `http://`.
The CA/Browser Forum Baseline Requirements mandate this: a fetch over TLS would
need the very certificate that is missing.
Apps that target Android 9 (API 28) or later **block cleartext HTTP by default**,
which would break the fetch in release builds. So the library fetches `http`
intermediates over a **raw socket**, which your app's `usesCleartextTraffic` and
network security config do not govern.
**You don't need to enable cleartext or add a network security config.**
A fetched certificate joins the chain when its subject matches
the issuer name of the certificate below it. The platform trust manager then
validates the completed chain, signatures included, against the system trust
anchors. So a forged or wrong certificate can only fail the handshake, never
weaken trust.
## Verify it worked
A silent success is hard to tell apart from "my problem was something else," so
confirm it explicitly:
1. **Confirm the factory is installed.** The `catch` above logs only on
*failure*, so **no warning at startup means the install did not throw**. In a
simple app, that is enough.
`setDefaultSSLSocketFactory` is last-write-wins (see [Caveats](#caveats)). If
another networking library sets its own default later, the fix stops working
with no warning. To catch that, compare the process default with the
`installedSslFactory` reference that the opt-in snippet stored.
Don't compare class names. `AiaTls.socketFactory()` returns a stock TLS socket
factory with the AIA-chasing trust manager, so its class looks the same as the
platform default.
Run the comparison after your other networking libraries have initialised,
for example on first playback or in a debug screen. In `onCreate`, next to the
install, it is always true and proves nothing.
::: code-group
```kotlin [Kotlin]
// Run after other networking libraries have initialised.
val active = HttpsURLConnection.getDefaultSSLSocketFactory() ===
MainApplication.installedSslFactory
Log.i("MainApplication", "AIA TLS active: $active")
```
```java [Java]
// Run after other networking libraries have initialised.
boolean active = HttpsURLConnection.getDefaultSSLSocketFactory()
== MainApplication.installedSslFactory;
Log.i("MainApplication", "AIA TLS active: " + active);
```
:::
2. **Confirm an `HttpURLConnection` request recovers.** Open
`https://incomplete-chain.badssl.com/` with `HttpsURLConnection` from your
app. Without the install it fails with
`SSLHandshakeException: ... Trust anchor for certification path not found`;
with it, it succeeds. A stream that fails in the player still fails (see
[The problem](#the-problem)).
### Still failing after install?
Work through these in order:
1. **Is the failure in playback?** The install does not reach the player (see
[The problem](#the-problem)). Fix the server's chain, or see
[Fix playback from the app](#fix-playback-from-the-app).
2. **Is it even a missing-intermediate case?** Re-run the
[diagnosis](#is-this-actually-your-problem). If the chain is complete, there's
no `CA Issuers` AIA pointer, or the root is genuinely untrusted/expired, this
fix can't repair it — that's a different problem.
3. **Did the AIA fetch fail?** When the chaser tries to fetch the intermediate and
can't, the library logs a warning:
```
AIA CA-issuer fetch failed: http://…/issuer.crt
```
Filter `adb logcat` for `AIA CA-issuer fetch failed`. If it appears, the fetch
was attempted but couldn't be reached — see the next point. (You do *not* need
to enable cleartext; the library's fetch already bypasses that policy.)
::: warning The logger starts with the playback service
The library plants its logging trees when its service first starts. A fetch
that fails **before** any playback has begun logs nothing, even though the
socket factory is process-wide and already in use.
If you see no line at all, start playback once and retry, or plant your own
tree at startup.
:::
4. **Reachable from your environment?** The fetch is a plain outbound request to
the `CA Issuers - URI` during the handshake, so a corporate proxy, VPN,
firewall, or a locked-down emulator network can block it. Confirm the URL
resolves by fetching it yourself — `curl -I "http://…/issuer.crt"` — from the
same network the device is on.
5. **Custom Network Security Config?** If your app ships a
`res/xml/network_security_config.xml` with custom trust anchors or pinning,
that's an unrelated cause of TLS failures — this fix won't override it.
## How it works
`AiaTls.socketFactory()` wraps the **platform default** trust manager. On the
happy path the default accepts the server-presented chain on the first try and
nothing extra happens. Only when the default *rejects* a chain does it:
1. read the leaf's AIA "CA Issuers" URL,
2. fetch the missing intermediate (over a raw socket for `http` URLs, so it works
regardless of your cleartext policy; cached for the process lifetime),
3. re-validate the completed chain **against the same system trust anchors**.
A fetched certificate joins the chain when its subject matches the issuer name
of the certificate before it. The system trust manager makes the final decision
on the completed chain, signatures included. So this can **only ever add a
missing intermediate — it can never weaken trust**.
Untrusted, expired, or self-signed roots still fail exactly as before.
## Caveats
* **Scope.** `setDefaultSSLSocketFactory` is process-wide, so it affects every
`HttpURLConnection`-based TLS connection in your app. It does not affect OkHttp
or a `WebView`, which keep their own TLS stacks, so it does not reach the
player (see [The problem](#the-problem)).
* **Last write wins.** If other code sets its own default afterwards, it
overrides this one.
* **First-connection latency on broken servers.** When a server omits its
intermediate, the first connection makes one extra HTTP request during the TLS
handshake. Well-configured servers pay nothing. The fetched intermediate is
cached for the **process lifetime only**, so the cost recurs once per cold
start for each broken server.
* **Not a cure-all.** It only rescues servers that omit an intermediate *and*
publish an AIA "CA Issuers" pointer that resolves to a trusted root. Servers
with no AIA extension, an unreachable intermediate, or a genuinely untrusted
root still fail.
* **The AIA fetch needs outbound network reachability.** Completing the chain
performs a plain HTTP request to the `CA Issuers` host during the handshake; a
proxy, VPN, or firewall that blocks it makes the fix look broken even on a
genuinely missing-intermediate server. See
[Still failing after install?](#still-failing-after-install) to diagnose.
* **Unrelated cause: custom Network Security Config.** A
`res/xml/network_security_config.xml` with custom trust anchors or certificate
pinning is a *different* source of TLS failures that this fix does not address.
## What you are opting into
Trust is never weakened. The chain is only ever *extended*, and the completed
chain is re-validated by the platform's own trust manager against the same
system anchors, so anything Android would have rejected is still rejected.
What you are accepting is an outbound request driven by a certificate that just
failed validation. The fetch URL comes from that certificate. So a rejected
handshake can cause a cleartext request to a **host, port and path of the
server's choosing**, including a loopback or LAN address.
That request is not subject to your app's `NetworkSecurityPolicy` (see
[The cleartext fetch is handled for you](#the-cleartext-fetch-is-handled-for-you)).
This is inherent to AIA chasing: browsers and Apple's Secure Transport do the
same thing, which is why the servers in question work everywhere except Android.
It is bounded rather than absent:
* the fetch happens **only** when the chain does not already reach one of your
trust anchors. Common non-path failures, such as an expired leaf or a hostname
mismatch, do not trigger one.
* that test is on the issuer name at the top of the chain. A chain that tops out
at a root your device does *not* carry is still chased, even if its real
problem is expiry. An example is a server that serves the retired DST Root CA
X3 cross-sign.
* the URL is rejected unless it is free of control characters, so it cannot
inject request lines of its own;
* the number of `CA Issuers` URLs tried per certificate, the size of a response
and the redirects followed per fetch are each capped;
* the whole chase runs under one 20-second wall-clock budget
(`AiaCertChaser.MAX_CHASE_MILLIS`). Every connect,
TLS handshake, read and redirect hop is clipped to the time remaining, and
nothing new starts once the budget has expired. So a hostile certificate can
hold one failed handshake for the length of the budget. One DNS lookup already in
flight when the budget expires can add its own duration, because Java has no
timeout for name resolution. No new lookup starts past the budget;
* the cache is bounded and holds only successful fetches;
* responses are never trusted on their say-so. A fetched certificate joins the
chain only if its subject matches the issuer name being chased, and the
completed chain still has to validate, signatures included.
If your threat model does not allow a failed handshake to trigger an outbound
connection at all, don't install this. Or install it on a single client of
your own (see [Advanced: custom OkHttp client](#advanced-custom-okhttp-client))
rather than as the process default.
## Advanced: custom OkHttp client
If you manage your own HTTP client instead of changing the process default, use
`AiaTls.trustManager()` to obtain the wrapped `X509TrustManager` and build a
matching `SSLSocketFactory` from it. OkHttp's `sslSocketFactory(...)` needs
**both** the factory and the trust manager:
::: code-group
```kotlin [Kotlin]
import com.audiobrowser.tls.AiaTls
import javax.net.ssl.SSLContext
import okhttp3.OkHttpClient
val trustManager = AiaTls.trustManager()
val sslContext = SSLContext.getInstance("TLS").apply {
init(null, arrayOf(trustManager), null)
}
val client = OkHttpClient.Builder()
.sslSocketFactory(sslContext.socketFactory, trustManager)
.build()
```
```java [Java]
import com.audiobrowser.tls.AiaTls;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
X509TrustManager trustManager = AiaTls.trustManager();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new X509TrustManager[] { trustManager }, null);
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), trustManager)
.build();
```
:::
This confines AIA chasing to that one client and leaves the process default
untouched. It does not reach the player (see [The problem](#the-problem)).
> **Lifecycle.** Each call to `AiaTls.socketFactory()` or `AiaTls.trustManager()`
> builds a new component with its **own** fetched-intermediate cache. Build one
> and reuse it; don't build one per request.
>
> The components are thread-safe: the fetch cache is a synchronized, bounded
> LRU. One instance is safe to install as the process default or to share
> across a client.