function initialize_media_controls() {
if (!("mediaSession" in navigator)) {
recordMessage(`No mediaSession available in this browser.`,2);
}
const audioElement = document.querySelector('audio');
const defaultSkipTime = 60; /* Default time to skip in seconds */
const controlActions = [
['play', () => { audioElement.play(); }],
['pause', () => { audioElement.pause(); }],
['previoustrack', () => { audioElement.currentTime = 0; }],
['nexttrack', () => { loadSongFromIndex(); }],
['stop', () => { audioElement.pause(); }],
['seekbackward', (details) => {
const skipTime = details.seekOffset || defaultSkipTime;
audioElement.currentTime = Math.max(audioElement.currentTime - skipTime, 0);
navigator.mediaSession.setPositionState({duration: audioElement.duration, playbackRate: audioElement.playbackRate, position: audioElement.currentTime});
}],
['seekforward', (details) => {
const skipTime = details.seekOffset || defaultSkipTime;
audioElement.currentTime = Math.min(audioElement.currentTime + skipTime, 0);
navigator.mediaSession.setPositionState({duration: audioElement.duration, playbackRate: audioElement.playbackRate, position: audioElement.currentTime});
}],
['seekto', (details) => {
if (details.fastSeek && 'fastSeek' in audioElement) {
audioElement.fastSeek(details.seekTime);
} else {
audioElement.currentTime = details.seekTime;
}
navigator.mediaSession.setPositionState({duration: audioElement.duration, playbackRate: audioElement.playbackRate, position: audioElement.currentTime});
}]
];
for (const [action, handler] of controlActions) {
try {
navigator.mediaSession.setActionHandler(action, handler);
} catch (error) {
recordMessage(`The action "${action}" is not supported by the media session yet.`,2);
}
}
try {
// Set playback event listeners
audioElement.addEventListener('play', () => { navigator.mediaSession.playbackState = 'playing'; });
audioElement.addEventListener('pause', () => { navigator.mediaSession.playbackState = 'paused'; });
}
catch (err) {
recordMessage(`Failed to set play/pause handlers for navigator.mediaSession.playbackState`,2);
}
}
For an example implementing the above function, refer to https://github.com/Noah-Jaffe/Mixcloud_player/blob/main/MUSICPLAYER.html. This function handles all audio media controls.
When using an Android device with Chrome, the functionality can be seen as depicted in the following image:
https://i.sstatic.net/gp61W.jpg