The MediaSession
interface of the Media Session API allows a web page to provide custom behaviors for standard media playback interactions, and to report metadata that can be sent by the user agent to the device or operating system for presentation in standardized user interface elements.
For example, a smartphone might have a standard panel in its lock screen that provides controls for media playback and information display. A browser on the device can use MediaSession
to make browser playback controllable from that standard/global user interface.
The following example creates a new media session and assigns action handlers to it:
if ('mediaSession' in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: 'Unforgettable',
artist: 'Nat King Cole',
album: 'The Ultimate Collection (Remastered)',
artwork: [
{ src: 'https://dummyimage.com/96x96', sizes: '96x96', type: 'image/png' },
{ src: 'https://dummyimage.com/128x128', sizes: '128x128', type: 'image/png' },
{ src: 'https://dummyimage.com/192x192', sizes: '192x192', type: 'image/png' },
{ src: 'https://dummyimage.com/256x256', sizes: '256x256', type: 'image/png' },
{ src: 'https://dummyimage.com/384x384', sizes: '384x384', type: 'image/png' },
{ src: 'https://dummyimage.com/512x512', sizes: '512x512', type: 'image/png' },
]
});
navigator.mediaSession.setActionHandler('play', function() { });
navigator.mediaSession.setActionHandler('pause', function() { });
navigator.mediaSession.setActionHandler('stop', function() { });
navigator.mediaSession.setActionHandler('seekbackward', function() { });
navigator.mediaSession.setActionHandler('seekforward', function() { });
navigator.mediaSession.setActionHandler('seekto', function() { });
navigator.mediaSession.setActionHandler('previoustrack', function() { });
navigator.mediaSession.setActionHandler('nexttrack', function() { });
navigator.mediaSession.setActionHandler('skipad', function() { });
}
The following example sets up two functions for playing and pausing, then uses them as callbacks with the relevant action handlers.
const actionHandlers = [
[
'play',
async function() {
await audioEl.play();
navigator.mediaSession.playbackState = "playing";
updateStatus(allMeta[index], 'Action: play | Track is playing...')
}
],
[
'pause',
() => {
audioEl.pause();
navigator.mediaSession.playbackState = "paused";
updateStatus(allMeta[index], 'Action: pause | Track has been paused...');
}
],
]
for (const [action, handler] of actionHandlers) {
try {
navigator.mediaSession.setActionHandler(action, handler);
} catch (error) {
console.log(`The media session action "${action}" is not supported yet.`);
}
}