From 55e22c6ffddfe986f785455f5587b1a525478878 Mon Sep 17 00:00:00 2001 From: Rem Helper Date: Wed, 19 Aug 2026 11:30:19 -0400 Subject: [PATCH] feat(web): add Media Session playback controls - Sync track metadata, artwork, playback state, and position - Support browser media controls for play, pause, seek, next, and previous --- apps/web/components/playback-provider.tsx | 58 ++++--- apps/web/hooks/use-media-session.ts | 181 ++++++++++++++++++++++ 2 files changed, 218 insertions(+), 21 deletions(-) create mode 100644 apps/web/hooks/use-media-session.ts diff --git a/apps/web/components/playback-provider.tsx b/apps/web/components/playback-provider.tsx index 20af76b..4c4d868 100644 --- a/apps/web/components/playback-provider.tsx +++ b/apps/web/components/playback-provider.tsx @@ -20,6 +20,7 @@ import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" import type { BrowseSong } from "@otunes/convex/types" import { playbackStreamPlan } from "@otunes/convex/playback-stream" +import { useMediaSession } from "@/hooks/use-media-session" import { supportsDolbyAtmosPlayback } from "@/lib/dolby-atmos-support" import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url" @@ -1027,6 +1028,38 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { setQueueOpen((open) => !open) }, []) + const skipNext = useCallback(async () => { + const isFinishingQueue = + repeatEnabled === "none" && queueSongIds.length <= 1 + if (isFinishingQueue) { + setIsPlaying(false) + seekTo(0) + } + await skipNextMutation() + if (isFinishingQueue) { + seekTo(0) + } + }, [repeatEnabled, queueSongIds.length, seekTo, skipNextMutation]) + + const skipPrevious = useCallback(async () => { + if (currentTime > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) { + seekTo(0) + return + } + await skipPreviousMutation() + }, [currentTime, seekTo, skipPreviousMutation]) + + useMediaSession({ + song: currentSong, + isPlaying: isPlaybackActive, + duration, + currentTime, + seekTo, + setIsPlaying, + skipNext, + skipPrevious, + }) + const value = useMemo( () => ({ queueSongIds: playback?.queueSongIds ?? [], @@ -1072,25 +1105,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { skipToQueueIndex: async (index) => { await skipToQueueIndexMutation({ index }) }, - skipNext: async () => { - const isFinishingQueue = - repeatEnabled === "none" && queueSongIds.length <= 1 - if (isFinishingQueue) { - setIsPlaying(false) - seekTo(0) - } - await skipNextMutation() - if (isFinishingQueue) { - seekTo(0) - } - }, - skipPrevious: async () => { - if (currentTime > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) { - seekTo(0) - return - } - await skipPreviousMutation() - }, + skipNext, + skipPrevious, dolbyAtmosSupported, }), [ @@ -1120,8 +1136,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { clearQueueMutation, reorderQueueMutation, skipToQueueIndexMutation, - skipNextMutation, - skipPreviousMutation, + skipNext, + skipPrevious, dolbyAtmosSupported, ] ) diff --git a/apps/web/hooks/use-media-session.ts b/apps/web/hooks/use-media-session.ts new file mode 100644 index 0000000..cef29df --- /dev/null +++ b/apps/web/hooks/use-media-session.ts @@ -0,0 +1,181 @@ +"use client" + +import * as React from "react" + +import type { BrowseSong } from "@otunes/convex/types" +import { albumCoverUrl } from "@/lib/cover-urls" + +const MEDIA_SESSION_ACTIONS = [ + "play", + "pause", + "previoustrack", + "nexttrack", + "seekto", +] as const + +function mediaSessionSupported() { + return typeof navigator !== "undefined" && "mediaSession" in navigator +} + +function setActionHandler( + action: MediaSessionAction, + handler: MediaSessionActionHandler | null +) { + try { + navigator.mediaSession.setActionHandler(action, handler) + } catch { + // The browser may not support every Media Session action. + } +} + +function artworkForSong(song: BrowseSong): MediaImage[] { + const src = new URL(albumCoverUrl(song.album.id), window.location.origin).href + return [ + { src, sizes: "96x96" }, + { src, sizes: "128x128" }, + { src, sizes: "192x192" }, + { src, sizes: "256x256" }, + { src, sizes: "384x384" }, + { src, sizes: "512x512" }, + ] +} + +function updatePositionState(duration: number, position: number) { + if (!("setPositionState" in navigator.mediaSession)) { + return + } + + if (!Number.isFinite(duration) || duration <= 0) { + try { + navigator.mediaSession.setPositionState() + } catch { + // Ignore browsers that reject clearing position state. + } + return + } + + const clampedPosition = Math.max(0, Math.min(position, duration)) + + try { + navigator.mediaSession.setPositionState({ + duration, + playbackRate: 1, + position: clampedPosition, + }) + } catch { + // Ignore invalid position state races (e.g. position > duration). + } +} + +export function useMediaSession({ + song, + isPlaying, + duration, + currentTime, + seekTo, + setIsPlaying, + skipNext, + skipPrevious, +}: { + song: BrowseSong | null + isPlaying: boolean + duration: number + currentTime: number + seekTo: (seconds: number) => void + setIsPlaying: (playing: boolean) => void + skipNext: () => void | Promise + skipPrevious: () => void | Promise +}) { + const songRef = React.useRef(song) + const seekToRef = React.useRef(seekTo) + const setIsPlayingRef = React.useRef(setIsPlaying) + const skipNextRef = React.useRef(skipNext) + const skipPreviousRef = React.useRef(skipPrevious) + + React.useEffect(() => { + songRef.current = song + seekToRef.current = seekTo + setIsPlayingRef.current = setIsPlaying + skipNextRef.current = skipNext + skipPreviousRef.current = skipPrevious + }) + + React.useEffect(() => { + if (!mediaSessionSupported()) { + return + } + + setActionHandler("play", () => { + if (!songRef.current) { + return + } + setIsPlayingRef.current(true) + }) + setActionHandler("pause", () => { + setIsPlayingRef.current(false) + }) + setActionHandler("previoustrack", () => { + void skipPreviousRef.current() + }) + setActionHandler("nexttrack", () => { + void skipNextRef.current() + }) + setActionHandler("seekto", (details) => { + if (typeof details.seekTime === "number") { + seekToRef.current(details.seekTime) + } + }) + + return () => { + for (const action of MEDIA_SESSION_ACTIONS) { + setActionHandler(action, null) + } + navigator.mediaSession.metadata = null + navigator.mediaSession.playbackState = "none" + updatePositionState(0, 0) + } + }, []) + + React.useEffect(() => { + if (!mediaSessionSupported()) { + return + } + + if (!song) { + navigator.mediaSession.metadata = null + return + } + + navigator.mediaSession.metadata = new MediaMetadata({ + title: song.title, + artist: song.artist.name, + album: song.album.title, + artwork: artworkForSong(song), + }) + }, [song]) + + React.useEffect(() => { + if (!mediaSessionSupported()) { + return + } + + navigator.mediaSession.playbackState = song + ? isPlaying + ? "playing" + : "paused" + : "none" + }, [isPlaying, song]) + + React.useEffect(() => { + if (!mediaSessionSupported()) { + return + } + + if (!song) { + updatePositionState(0, 0) + return + } + + updatePositionState(duration, currentTime) + }, [song, duration, currentTime]) +} -- 2.54.1