Skip to main content

setMediaSession

setMediaSession(id: string, info?: MediaSessionInfo): void;

Hand one sound to the operating system's media controls.

This puts a title and cover art on a phone's lock screen and in the notification shade, and it makes the play/pause key on a keyboard and the buttons on a headset control your audio. For anything long, like a podcast, an audiobook or a radio stream, listeners expect their phone to behave like a podcast player. Without this they get a silent notification and dead buttons.

Works for a streamed sound and a buffered one alike. Call it again with new metadata when the track changes, and clearMediaSession when playback is finished.

ParameterTypeDescription
idstringThe sound the controls should drive
infoMediaSessionInfo (optional)Metadata and skip offsets

MediaSessionInfo

PropertyTypeDefaultDescription
titlestringShown as the main line
artiststringShown underneath
albumstringShown on some platforms
artwork{ src, sizes?, type? }[]At least one 512x512 image works best everywhere
seekBackwardOffsetnumber15Seconds the skip-back button jumps
seekForwardOffsetnumber30Seconds the skip-forward button jumps
onPreviousTrack() => voidWires the previous-track button. Leave it out and the button stays dark
onNextTrack() => voidWires the next-track button

Example

import { SoundHub } from 'soundhub';

const soundHub = new SoundHub();

await soundHub.loadStream('episode-42', '/audio/episode-42.mp3', {
trackProgress: true,
});

soundHub.play('episode-42');

soundHub.setMediaSession('episode-42', {
title: 'Episode 42: naming things',
artist: 'The Podcast',
album: 'Season 3',
artwork: [
{ src: '/cover-192.png', sizes: '192x192', type: 'image/png' },
{ src: '/cover-512.png', sizes: '512x512', type: 'image/png' },
],
onNextTrack: () => playEpisode(43),
onPreviousTrack: () => playEpisode(41),
});

What it wires up

ControlWhat happens
PlayResumes if paused, otherwise starts from the beginning
Pausepause
Stopstop
Skip backwardseek back by seekBackwardOffset
Skip forwardseek forward by seekForwardOffset
Scrubberseek to the dragged position
Previous and nextYour onPreviousTrack and onNextTrack, if you passed them

The playback state and the scrubber position are kept in step for you. Every event soundhub dispatches for this sound also updates what the operating system shows, so the lock screen never disagrees with your own interface.

note

trackProgress: true keeps the scrubber moving smoothly, because the position is refreshed on each progress event. Without it the lock screen still works, but the scrubber only jumps when something else happens.


Support

Media Session is available in current Chrome, Edge, Firefox and Safari, on desktop and mobile. Where it is missing this method logs in debug mode and returns. Nothing else changes and your audio plays as normal.