> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# LynxAudioPlayer

Plays **audio**, such as a podcast, music, an audiobook or a meditation, and puts it on the **lock screen**, in Control Center and in Android's media notification, whose buttons control it. `import { LynxAudioPlayer } from '@blotch/angular-lynx';`

Lynx has no `<audio>` element and no `HTMLAudioElement`, so this is how an app plays sound. Every app has the player: it needs no permission.

## Usage

```typescript
import { DecimalPipe } from '@angular/common';
import { Component, inject } from '@angular/core';
import { LYNX_ELEMENTS, LynxAudioPlayer } from '@blotch/angular-lynx';

@Component({
  selector: 'app-episode',
  imports: [LYNX_ELEMENTS, DecimalPipe],
  template: `
    <text>{{ player.track()?.title }}</text>
    <text
      >{{ player.position() | number: '1.0-0' }} /
      {{ player.duration() | number: '1.0-0' }} s</text
    >
    @if (player.state() === 'playing') {
      <view (click)="player.pause()"><text>Pause</text></view>
    } @else {
      <view (click)="player.play()"><text>Play</text></view>
    }
    <view (click)="player.seek(player.position() + 30)"
      ><text>+30 s</text></view
    >
  `,
})
export class Episode {
  readonly player = inject(LynxAudioPlayer);

  constructor() {
    void this.player.load({
      url: 'https://example.com/episodes/42.mp3',
      title: 'Signals in depth',
      artist: 'The Angular Show',
      artwork: 'https://example.com/episodes/42.jpg',
    });
  }
}
```

`load()` resolves once the track is ready to play: `state` is then `paused` at its start, and `duration` says how long it is. `play()` plays it, from where it paused, or from its start once it has `ended`.

The `url` can be:

- an `https:` URL,
- a file the app bundles: import it (`import rain from './rain.mp3';`), which gives its URL,
- a `file://` URL, such as a [`LynxAudioRecorder`](/api/angular-lynx/hardware/audio-recorder.md) clip's `uri`.

The phone plays any format it knows, such as MP3, AAC (`.m4a`) and WAV.

## Play in the background

Every app plays while it's on the screen, and pauses when it leaves: a `play()` while it's in the background rejects with `failed`, and the lock screen's Play does nothing. To play on with the app in the background and the phone locked, add `backgroundAudio` to the `build` target's options in angular.json:

```json title="angular.json"
"options": {
  "backgroundAudio": true
}
```

What it adds:

- **iOS:** the `audio` background mode (`UIBackgroundModes`).
- **Android:** a media playback foreground service, whose notification holds the controls, with the `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_MEDIA_PLAYBACK` and `WAKE_LOCK` permissions. Android grants them when the app installs, without asking.

Turn it on only for an app that's listened to with the screen off:

- **App Review** rejects an app with the `audio` mode that plays nothing in the background (guideline 2.5.4).
- **Google Play** asks what the foreground service is for, in the Play Console's App content page, for an app that targets Android 14.

See [Turn on device features](/guide/native-apps/device-features.md) for every setting.

## The lock screen

While a track is loaded, the lock screen, Control Center, Android's notification, and headphones', a watch's and a car's buttons control it. They show the track's `title`, `artist`, `album` and `artwork`.

Play, pause and the slider act on the player by themselves. **Next and previous** show only while the app takes them, with `onRemoteCommand()`:

```typescript
import { Component, inject, signal } from '@angular/core';
import {
  type AudioTrack,
  LYNX_ELEMENTS,
  LynxAudioPlayer,
} from '@blotch/angular-lynx';

@Component({
  selector: 'app-playlist',
  imports: [LYNX_ELEMENTS],
  template: `<view (click)="open(0)"><text>Play all</text></view>`,
})
export class Playlist {
  readonly #player = inject(LynxAudioPlayer);
  readonly #index = signal(0);
  readonly episodes: readonly AudioTrack[] = [
    {
      url: 'https://example.com/episodes/41.mp3',
      title: 'Zoneless in practice',
    },
    { url: 'https://example.com/episodes/42.mp3', title: 'Signals in depth' },
  ];

  constructor() {
    // Removed with the component.
    this.#player.onRemoteCommand('next', () => this.open(this.#index() + 1));
    this.#player.onRemoteCommand('previous', () =>
      this.open(this.#index() - 1),
    );
  }

  async open(index: number) {
    const episode = this.episodes[index];
    if (!episode) return;
    this.#index.set(index);
    await this.#player.load(episode);
    await this.#player.play();
  }
}
```

A handler for `play`, `pause` or `seek` replaces what the button does, as a web page's `navigator.mediaSession.setActionHandler()` does. `seek`'s handler gets the position the person moved the slider to, in seconds.

The handler goes when the component or service that added it is destroyed, or when you call the function `onRemoteCommand()` returns. Outside an injection context, pass `{ injector }`. With two handlers for the same command, the newer one takes it until it's removed.

`stop()` takes the track off the lock screen and out of the notification.

## Interruptions

The player pauses by itself, and `state` turns `paused`, when:

- a phone call or another app's audio takes over (iOS plays on after a call if iOS says to),
- headphones are unplugged,
- the app leaves the screen, without `backgroundAudio`.

Taking the audio pauses other apps' music, and lets it play on again after `stop()`.

## Methods

| Method                                        | Returns         | Description                                                                                                   |
| --------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------- |
| `load(track)`                                 | `Promise<void>` | Loads a track, in place of the one before. Resolves once it's ready to play                                   |
| `play()`                                      | `Promise<void>` | Plays the loaded track                                                                                        |
| `pause()`                                     | `void`          | Pauses it                                                                                                     |
| `seek(seconds)`                               | `void`          | Moves to `seconds` into the track                                                                             |
| `stop()`                                      | `void`          | Stops it and lets it go: `state` turns `idle`, and the lock screen no longer shows it                         |
| `onRemoteCommand(command, handler, options?)` | `() => void`    | Takes a lock-screen button: `play`, `pause`, `next`, `previous` or `seek`. Returns a function that removes it |

| Signal     | Type                                    | Description                                                                                           |
| ---------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `state`    | `Signal<AudioPlayerState>`              | `idle`, `loading`, `playing`, `paused`, `ended` or `error`                                            |
| `position` | `Signal<number>`                        | How far in playback is, in seconds, about four times a second while it plays (once in the background) |
| `duration` | `Signal<number>`                        | How long the track is, in seconds: the track's `duration` until the file says, and 0 for neither      |
| `track`    | `Signal<AudioTrack \| undefined>`       | The track `load()` was last given                                                                     |
| `error`    | `Signal<AudioPlayerError \| undefined>` | Why it couldn't load or play on, while `state` is `error`                                             |

`state` is `loading` while `load()` fetches the track, and whenever playback waits for more of it.

### `AudioTrack`

| Field      | Type     | Description                                                                                    |
| ---------- | -------- | ---------------------------------------------------------------------------------------------- |
| `url`      | `string` | Where the audio is: `https:`, a file the app bundles, or `file://`                             |
| `title`    | `string` | The name the lock screen shows                                                                 |
| `artist`   | `string` | Who made it, under the title                                                                   |
| `album`    | `string` | The album, or the podcast or book it's from                                                    |
| `artwork`  | `string` | An image's URL (`https:`, or a file the app bundles) beside the title. Square images look best |
| `duration` | `number` | How long it plays, in seconds, until the file says                                             |

### `AudioPlayerError`

`load()` and `play()` reject with an `AudioPlayerError`, and `error` holds one for a track that stopped. Its `code` is one of:

| Code                 | When                                                                     |
| -------------------- | ------------------------------------------------------------------------ |
| `unavailable`        | The host can't play: Lynx Explorer                                       |
| `network`            | The file couldn't be fetched: no connection, an HTTP error, no such file |
| `unsupported-format` | The phone can't play what it fetched                                     |
| `aborted`            | A newer `load()` or a `stop()` replaced the track before it was ready    |
| `failed`             | Anything else, such as `play()` with nothing loaded                      |

## Platform support

| Platform      | Support                                                                                                                                |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| iOS           | `AVPlayer` in the `playback` audio session, which the silent switch doesn't mute. `MPNowPlayingInfoCenter` and `MPRemoteCommandCenter` |
| Android       | Media3's `ExoPlayer` and `MediaSession`. With `backgroundAudio`, a `MediaSessionService` and its notification                          |
| Web preview   | An `<audio>` element on the page, and `navigator.mediaSession` for the browser's media controls                                        |
| Lynx Explorer | `unavailable`                                                                                                                          |

The web preview plays only after the person has interacted with the page, as browsers require: a `play()` before that rejects with `failed`.

## Testing

The testing library fakes the player. A track loads at once and plays by the clock, so [`audioPlayback()`](/api/testing-library/fakes/sensors.md#audioplayback) says where it is, and [`pressRemoteCommand()`](/api/testing-library/fakes/sensors.md#pressremotecommand) presses a lock-screen button:

```typescript
vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] });
setAudioFile('https://example.com/episodes/42.mp3', { duration: 1800 });
await render(Episode);
fireEvent.tap(screen.getByText('Play'));
await waitForUpdate();
vi.advanceTimersByTime(10_000);
expect(audioPlayback()?.position).toBe(10);
pressRemoteCommand('pause');
await waitForUpdate();
expect(screen.getByText('Play')).toBeInTheDocument();
```

## Related

- [`LynxAudioRecorder`](/api/angular-lynx/hardware/audio-recorder.md): record a clip to play back
- [Turn on device features](/guide/native-apps/device-features.md): `backgroundAudio` and the other opt-in build options
- [`LynxAppState`](/api/angular-lynx/device/app-state.md): whether the app is on the screen
