How to Add Media Session to Your Website

Media Session allows you to customize how your audio is displayed on a device. It gives you control of what artwork is shown and what actions are allowed. This allows users more control on how a song or podcast is played without having your website opened. In this blog we will learn how to add Media Session to your website.

Jordan Wu profile picture

Jordan Wu

4 min·Posted 

Sunset Over a Body of Water Image.
Sunset Over a Body of Water Image.
Table of Contents

What is a Media Session?

The Media Session API provides a way for you to send rich metadata to a device. This includes the title, artist name, album, and artwork. It provides many action handlers to handle actions such as play next audio. A good example of what functionality it provides is how users are able to interact with Spotify while the app isn't open.

How to Add Media Session Metadata

A media session takes a MediaMetadata object and its information about the audio being played. When audio is loaded on your website you should send the rich metadata to the media session, navigator.mediaSession.metadata. Be sure to check that mediaSession exists on navigator.

if ('mediaSession' in navigator) {
  navigator.mediaSession.metadata = new MediaMetadata({
    title: 'Nothing But the Radio',
    src: 'https://tracks.jordanwu.xyz/black-bear-the-sex-mixtape/Nothin-But-the-Radio.mp3',
    artist: 'Blackbear',
    album: 'Sex the Mixtape',
    thumbnail: 'https://images.jordanwu.xyz/albums/black-bear-the-sex-mixtape/black-bear-sex-the-mixtape.jpeg',
    thumbnailSmall:
      'https://images.jordanwu.xyz/albums/black-bear-the-sex-mixtape/black-bear-sex-the-mixtape-96x96.jpeg',
    artworks: [
      {
        src: 'https://images.jordanwu.xyz/albums/black-bear-the-sex-mixtape/black-bear-sex-the-mixtape-96x96.jpeg',
        sizes: '96x96',
        type: 'image/jpeg',
      },
      {
        src: 'https://images.jordanwu.xyz/albums/black-bear-the-sex-mixtape/black-bear-sex-the-mixtape-128x128.jpeg',
        sizes: '128x128',
        type: 'image/jpeg',
      },
      {
        src: 'https://images.jordanwu.xyz/albums/black-bear-the-sex-mixtape/black-bear-sex-the-mixtape-192x192.jpeg',
        sizes: '192x192',
        type: 'image/jpeg',
      },
      {
        src: 'https://images.jordanwu.xyz/albums/black-bear-the-sex-mixtape/black-bear-sex-the-mixtape-192x192.jpeg',
        sizes: '256x256',
        type: 'image/jpeg',
      },
      {
        src: 'https://images.jordanwu.xyz/albums/black-bear-the-sex-mixtape/black-bear-sex-the-mixtape-384x384.jpeg',
        sizes: '384x384',
        type: 'image/jpeg',
      },
      {
        src: 'https://images.jordanwu.xyz/albums/black-bear-the-sex-mixtape/black-bear-sex-the-mixtape-512x512.jpeg',
        sizes: '512x512',
        type: 'image/jpeg',
      },
    ],
  })
}

For the best user experience on different device screen sizes be sure to include the artwork in many different sizes.

How to Update Playback State

The navigator.mediaSession has a property called playbackState that is used to determine the current state of the audio. It has the following values:

none: The browsing context doesn't currently know the current playback state, or the playback state is not available at this time.

paused: The browser's media session is currently paused. Playback may be resumed.

playing: The browser's media session is currently playing media, which can be paused.

if ('mediaSession' in navigator) {
  if (playing) {
    navigator.mediaSession.playbackState = 'playing'
  } else {
    navigator.mediaSession.playbackState = 'paused'
  }
}

Be sure to update this state as the user interacts with your audio and in action handlers in the next section.

How to Set Action Handlers

Once you added metadata and tracking playbackState site. The next step is to set action handlers for the Media Session. This allows the users to engage with your audio using the device's built-in onscreen media controls, such as play, stop, or seek buttons. This is done using setActionHandler.

setActionHandler(type, callback)

There are many types of actions that you can handle. You can find the list in setActionHandler. In this section you will go over the most commonly used actions you can find when using Spotify.

nexttrack: Advances playback to the next track.

pause: Pauses playback of the media.

play: Begins (or resumes) playback of the media.

previoustrack: Moves back to the previous track.

seekto: Moves the playback position to the specified time within the media.

if ('mediaSession' in navigator) {
  navigator.mediaSession.metadata = new MediaMetadata({
    album: currentTrack.album,
    artist: currentTrack.artist,
    artwork: currentTrack.artworks,
    title: currentTrack.title,
  })

  const actionHandlers: ActionHandlersTuple[] = [
    [
      'play',
      () => {
        play()
      },
    ],
    [
      'pause',
      () => {
        pause()
      },
    ],
    [
      'stop',
      () => {
        pause()
      },
    ],
    [
      'seekto',
      (details) => {
        const audioPlayerPlayOrPauseButton = document.getElementById(
          'audio-player-play-or-pause-button'
        )
        const playing = audioPlayerPlayOrPauseButton.getAttribute('data-audio-playing') == 'true'
        const audioPlayerBottomProgressSliderInput = document.getElementById(
          'audio-player-bottom-progress-slider-input'
        )
        const duration = +audioPlayerBottomProgressSliderInput.getAttribute('data-audio-duration')
        if (details.seekTime >= 0 && details.seekTime < duration) {
          seek(details.seekTime)
          if (!playing) {
            setMediaSessionPositionState(details.seekTime, duration)
          }
        }
      },
    ],
    [
      'previoustrack',
      () => {
        const audioPlayerPlayOrPauseButton = document.getElementById(
          'audio-player-play-or-pause-button'
        )
        const playing = audioPlayerPlayOrPauseButton.getAttribute('data-audio-playing') == 'true'
        const audioPlayerBottomProgressSliderInput = document.getElementById(
          'audio-player-bottom-progress-slider-input'
        )
        const duration = +audioPlayerBottomProgressSliderInput.getAttribute('data-audio-duration')

        setShouldAutoPlay(getAutoPlayForNextOrPreviousTrack(playing))

        if (getPosition() < 3) {
          if (trackIndex === 0) {
            setTrackIndex(lastTrackIndex)
          } else {
            setTrackIndex(trackIndex - 1)
          }
        } else {
          seek(0)
          setMediaSessionPositionState(0, duration)
        }
      },
    ],
    [
      'nexttrack',
      () => {
        const audioPlayerPlayOrPauseButton = document.getElementById(
          'audio-player-play-or-pause-button'
        )
        const playing = audioPlayerPlayOrPauseButton.getAttribute('data-audio-playing') == 'true'

        setShouldAutoPlay(getAutoPlayForNextOrPreviousTrack(playing))

        setTrackIndex((index) => {
          if (index === lastTrackIndex) return 0
          return index + 1
        })
      },
    ],
  ]

  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.`)
    }
  }
}

You should add it when your audio is loaded and you can use data attributes to get the duration and playing state of the audio. We will talk about setMediaSessionPositionState in the next section.

How to Set Media Session Position State

It's important that the timer on the audio updates correctly as it's playing. To do that there's setPositionState on the Media Session. This method allows you to update the current playback position, speed of the playback, and the duration of the audio.

const setMediaSessionPositionState = (position, duration) => {
  if (
    'mediaSession' in navigator &&
    navigator.mediaSession.metadata &&
    position >= 0 &&
    duration >= 0 &&
    position <= duration
  ) {
    navigator.mediaSession.setPositionState({
      duration: duration,
      position: position,
    })
  }
}

I created a function called setMediaSessionPositionState to update the position state. You would want to make sure both position and duration are positive number including 0 and that the position should never be greater than the duration. Be sure to call this method when the audio is playing. You can use timeupdate event listner on a audio element or if you are using React a useEffect to set position state.

That's everything you would need to add Media Session to your website!

Media Session Mobile Notification
Media Session Mobile Notification
Media Session Mobile Locked Screen
Media Session Mobile Locked Screen

About the Author

Jordan Wu profile picture
Jordan is a full stack engineer with years of experience working at startups. He enjoys learning about software development and building something people want. What makes him happy is music. He is passionate about finding music and is an aspiring DJ. He wants to create his own music and in the process of finding is own sound.
Email icon image
Stay up to date

Get notified when I publish something new, and unsubscribe at any time.