Skip to content

Add MediaSession metadata for audio playback #458

@JeremyLoh

Description

@JeremyLoh

For playback of audio on mobile devices, the Lock Screen or notification tray displays no information about the podcast that is currently playing

Use MediaSession API to set the metadata for the PodcastPlayer and Radio station player

Create a custom react hook for setting audio playback metadata

image

UPDATE: Fix for PR is not working #459

  • The useEffect runs once when the component mounts, but it does not react to source changes or playback. Safari on iOS requires a user gesture before audio playback and the Media Session metadata only appears if it is set after the audio element is loaded and playing
  • To fix
    • Set an event listener on the audio ref in the useEffect, it should add the audio metadata on the play event
import { RefObject, useEffect } from "react"

function useAudioMetadata(
  mediaRef: RefObject<HTMLMediaElement | null>,
  init: MediaMetadataInit
) {
  useEffect(() => {
    if (
      mediaRef == null ||
      mediaRef.current == null ||
      !("mediaSession" in navigator)
    ) {
      return
    }
    const media = mediaRef.current
    const handlePlay = () => {
      navigator.mediaSession.metadata = new MediaMetadata(init)
    }

    if (!media.paused) {
      handlePlay() // apply immediately only if the element is already playing
    }
    // reapply on every play / playing
    media.addEventListener("play", handlePlay, { once: true })
    media.addEventListener("playing", handlePlay)

    return () => {
      media.removeEventListener("play", handlePlay)
      media.removeEventListener("playing", handlePlay)
    }
  }, [mediaRef, init])
}

export default useAudioMetadata

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions