For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/angular-lynx/hardware/audio-player.md.

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

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 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:

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 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():

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

MethodReturnsDescription
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()voidPauses it
seek(seconds)voidMoves to seconds into the track
stop()voidStops it and lets it go: state turns idle, and the lock screen no longer shows it
onRemoteCommand(command, handler, options?)() => voidTakes a lock-screen button: play, pause, next, previous or seek. Returns a function that removes it
SignalTypeDescription
stateSignal<AudioPlayerState>idle, loading, playing, paused, ended or error
positionSignal<number>How far in playback is, in seconds, about four times a second while it plays (once in the background)
durationSignal<number>How long the track is, in seconds: the track's duration until the file says, and 0 for neither
trackSignal<AudioTrack | undefined>The track load() was last given
errorSignal<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

FieldTypeDescription
urlstringWhere the audio is: https:, a file the app bundles, or file://
titlestringThe name the lock screen shows
artiststringWho made it, under the title
albumstringThe album, or the podcast or book it's from
artworkstringAn image's URL (https:, or a file the app bundles) beside the title. Square images look best
durationnumberHow 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:

CodeWhen
unavailableThe host can't play: Lynx Explorer
networkThe file couldn't be fetched: no connection, an HTTP error, no such file
unsupported-formatThe phone can't play what it fetched
abortedA newer load() or a stop() replaced the track before it was ready
failedAnything else, such as play() with nothing loaded

Platform support

PlatformSupport
iOSAVPlayer in the playback audio session, which the silent switch doesn't mute. MPNowPlayingInfoCenter and MPRemoteCommandCenter
AndroidMedia3's ExoPlayer and MediaSession. With backgroundAudio, a MediaSessionService and its notification
Web previewAn <audio> element on the page, and navigator.mediaSession for the browser's media controls
Lynx Explorerunavailable

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() says where it is, and pressRemoteCommand() presses a lock-screen button:

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();