BackgroundAudio

Plays one audio record that goes on while the app is in the background and the screen is locked — an audio guide, a podcast, a lesson — from the background-audio plugin. The system shows the record with its title and a play / pause button (the lock screen, the notification); a headset's button, an incoming call and headphones pulled out are answered without the app's code. For a sound of the screen that stops with the app use AudioPlayer (media.md), for game sounds audio (audio.md).

  • keep an audio guide playing when the screen is locked
  • play audio in the background while the app is minimized
  • show the track's title and a pause button on the lock screen
  • show a loading spinner until the audio starts, and a failure when it cannot play
  • show the playback position and a seek bar
  • go on from where the listener stopped
  • fall back to AudioPlayer where background audio is not available (BackgroundAudio.supported)

Platforms: iOS and Android in the le.codes viewer app, the web and the web player (the browser decides what a hidden tab plays); not on desktop or in headless tests, and not yet in an iOS or Android app built with lecodes app — check BackgroundAudio.supported.

At a glance

TypeScript
const state = signal<BackgroundAudioState>('idle')
const position = signal(0)
const length = signal(0)

BackgroundAudio.on('state', ({ value }) => { state.value = value })        // loading, playing, paused, ended, failed
BackgroundAudio.on('duration', ({ value }) => { length.value = value })    // seconds, once the record is known
BackgroundAudio.on('position', ({ value }) => { position.value = value })  // seconds, twice a second while it plays

const toggle = () => {
  if (state.value === 'idle') BackgroundAudio.play({ src: 'https://example.com/guide.mp3', title: 'The old bridge', artist: 'City guide' })
  else if (state.value === 'playing' || state.value === 'loading') BackgroundAudio.pause()
  else BackgroundAudio.resume()      // after 'ended': from the start; after 'failed': the record is asked for again
}

UIScreen(
  UIButton(UIText(() => state.value === 'playing' ? 'Pause' : state.value === 'loading' ? '…' : 'Play')).onClick(toggle),
  UIText(() => `${Math.floor(position.value)} / ${Math.floor(length.value)} s`),
  UIButton(UIText('Stop')).onClick(() => { BackgroundAudio.stop() }),
).style({ pt: 'safe-top', p: 20, gap: 12 }).open()

Add background audio to the app: app.json plugins

BackgroundAudio needs the background-audio plugin, listed in the app's app.json (one list for every platform; the le.codes viewer app has it whatever the list says):

JSON
{ "plugins": { "background-audio": "*" } }
  • The plugin is what declares background playback to the system in an app's own build: the audio background mode in the iOS Info.plist, the media playback service and its permissions in the Android manifest. List it only in an app that plays in the background — the App Store rejects an app that declares the mode and does not use it, and Google Play asks what the service is for.
  • Without the plugin BackgroundAudio.supported is false and a call rejects.

Play a record: play, pause, resume, stop

TypeScript
BackgroundAudio.play(track: { src: string, title: string, artist?: string, position?: number }): Promise<void>
BackgroundAudio.pause(): Promise<void>
BackgroundAudio.resume(): Promise<void>
BackgroundAudio.stop(): Promise<void>
  • One record at a time: play lets the record that played go. src is an http / https url; title and artist are what the system shows; position is where it starts, in seconds.
  • play resolves once the host took the record — what becomes of it is the state event: 'loading', then 'playing' or 'failed'.
  • resume goes on after a pause, from the start after 'ended', and asks for the record again after 'failed'.
  • stop lets the record go: the system's player disappears, the state is 'idle'.
  • The record plays until it is stopped — a screen that closes does not stop it. Stop it where the app has no way left to show it.

Follow what the player does: the state event

TypeScript
BackgroundAudio.on('state', ({ value }) => …)   // 'idle' | 'loading' | 'playing' | 'paused' | 'ended' | 'failed'
BackgroundAudio.off('state', listener)
  • The state changes by the app's calls and without them: the lock screen's button, a headset, a call that interrupts the record, its end. Draw the play button from the event, never from the call the app made last.
  • 'loading' also comes in the middle of a record when the network cannot keep up.

Show the length and the position: the duration and position events

TypeScript
BackgroundAudio.on('duration', ({ value }) => …)   // seconds: once per record, when its length is known
BackgroundAudio.on('position', ({ value }) => …)   // seconds: about twice a second while it plays
BackgroundAudio.seek(seconds): Promise<void>
  • position is sent only while it has a listener: the host does not call into the app for a position nobody shows. Add the listener when the player is on screen, take it off (off) when it is not. The first value comes at once, and one after everything that moves the record — a seek, a pause, its end.
  • seek is clamped to the record; before the length is known it sets where the record starts.

Come back from the background: status

TypeScript
BackgroundAudio.status(): Promise<{ state: BackgroundAudioState, duration: number, position: number }>

The app's code does not run in the background, and no position is sent there. When the app comes back (app.md, the resume event) read everything at once:

TypeScript
app.addEventListener('resume', () => {
  BackgroundAudio.status().then(({ state, position, duration }) => { /* redraw the player */ })
})

Do not pause the record on the app's pause event: that is the moment it is meant to play on.

Where background audio is not available: supported

TypeScript
const main = () => {
  const src = 'https://example.com/guide.mp3'
  if (BackgroundAudio.supported) BackgroundAudio.play({ src, title: 'The old bridge' })
  else new AudioPlayer(src).play()      // the desktop: it plays while the app is open
}
main()

See also

  • media.md — AudioPlayer: a sound that lives with the screen
  • audio.md — game audio
  • app.md — the pause / resume events