Skip to content

Media session

Checked against c1b2fa4 on 2026-11-10. The files it covers are unchanged since.

niso implements the web’s Media Session API, and the hosts turn it into the platform’s own media controls: Now Playing on the Lock Screen and in Control Center on Apple platforms, the media notification on Android, and Now Playing in CarPlay. You write the same code as on the web. examples/radio is a live radio player that does this.

Use an <audio> or <video> element. The host plays it natively (an AVPlayer on Apple platforms, Media3 on Android; the page’s element is told what happens through niso_dom_media_update) and keeps it playing while the app is in the background.

Set navigator.mediaSession.metadata when you know what’s playing:

examples/radio/App.svelte
navigator.mediaSession.metadata = new MediaMetadata({
title: song.title, artist: song.artist, album: song.album,
artwork: art ? [{ src: art, sizes: '500x500', type: 'image/jpeg' }] : [],
});

examples/radio/App.svelte, line 33

Register handlers for the actions you support. The radio supports three:

examples/radio/App.svelte
navigator.mediaSession.setActionHandler('play', () => audio.play());
navigator.mediaSession.setActionHandler('pause', () => audio.pause());
navigator.mediaSession.setActionHandler('stop', () => audio.pause());

examples/radio/App.svelte, line 49

niso knows the actions play, pause, stop, seekbackward, seekforward, previoustrack, nexttrack and seekto (crates/niso-core/src/media.rs). The system shows controls only for the actions you handle, and without a seekto handler it offers no scrubbing.

setPositionState sets the progress the system shows. Set it again when playback starts or stops and when the track changes:

examples/radio/App.svelte
navigator.mediaSession.setPositionState({ duration: song.duration, playbackRate: 1, position });

examples/radio/App.svelte, line 64

Terminal window
hosts/apple/build.sh radio
hosts/android/build.sh radio

The radio streams from the network, so it needs a connection. To make its stations a CarPlay list as well, see Surfaces.