Huy's Notes
Use MediaSession for audio player

Use MediaSession for audio player

If you're building a web-based audio player, you probably using <audio> tag, with the recent Chrome and Firefox's Media Control feature, you'll notice when your app is playing, the Media Control show something weird like this:

Many other web-based music players like Youtube Music or Spotify has it works so well.

To support the browser's Media Control, you need to implement MediaSession, for example, you'll need to implement the following two methods to let the browser's Media Control skip to next or previous track in the playlist:

navigator.mediaSession.setActionHandler('previoustrack', function() {
  ...
});

navigator.mediaSession.setActionHandler('nexttrack', function() {
  ...
});

For styling the media player, to make it match the currently playing song:

navigator.mediaSession.metadata = new MediaMetadata({
  title: track.title,
  artist: track.artist,
  album: track.album,
  artwork: track.artwork
});

The end result would be something like this:

References:

Referred in


If you think this note resonated, be it positive or negative, please feel free to send me an email and we can talk.