Cleanup media session handling on the web

This commit is contained in:
Zoe Roux 2024-07-01 03:45:36 +00:00
parent edf5d0c613
commit 39dd30b762
No known key found for this signature in database

View File

@ -149,19 +149,7 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
nativeRef.current.playbackRate = rate; nativeRef.current.playbackRate = rate;
}, [rate]); }, [rate]);
useMediaSession( useMediaSession(source?.metadata, nativeRef, showNotificationControls);
source?.metadata,
nativeRef,
useMemo(
() => ({
seek,
resume,
pause,
}),
[seek, resume, pause],
),
showNotificationControls,
);
return ( return (
<video <video
@ -255,11 +243,6 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
const useMediaSession = ( const useMediaSession = (
metadata: VideoMetadata | undefined, metadata: VideoMetadata | undefined,
nativeRef: RefObject<HTMLVideoElement>, nativeRef: RefObject<HTMLVideoElement>,
actions: {
seek: (time: number) => void;
pause: () => void;
resume: () => void;
},
showNotification: boolean, showNotification: boolean,
) => { ) => {
const isPlaying = !nativeRef.current?.paused ?? false; const isPlaying = !nativeRef.current?.paused ?? false;
@ -286,19 +269,24 @@ const useMediaSession = (
return; return;
} }
const seekRelative = (offset: number) => { const seekTo = (time: number) => {
if (!nativeRef.current) { if (nativeRef.current) {
return; nativeRef.current.currentTime = time;
}
};
const seekRelative = (offset: number) => {
if (nativeRef.current) {
nativeRef.current.currentTime = nativeRef.current.currentTime + offset;
} }
actions.seek(nativeRef.current.currentTime + offset);
}; };
const mediaActions: [ const mediaActions: [
MediaSessionAction, MediaSessionAction,
MediaSessionActionHandler | null, MediaSessionActionHandler | null,
][] = [ ][] = [
['play', () => actions.resume()], ['play', () => nativeRef.current?.play()],
['pause', () => actions.pause()], ['pause', () => nativeRef.current?.pause()],
[ [
'seekbackward', 'seekbackward',
(evt: MediaSessionActionDetails) => (evt: MediaSessionActionDetails) =>
@ -309,10 +297,7 @@ const useMediaSession = (
(evt: MediaSessionActionDetails) => (evt: MediaSessionActionDetails) =>
seekRelative(evt.seekOffset ? evt.seekOffset : 10), seekRelative(evt.seekOffset ? evt.seekOffset : 10),
], ],
[ ['seekto', (evt: MediaSessionActionDetails) => seekTo(evt.seekTime!)],
'seekto',
(evt: MediaSessionActionDetails) => actions.seek(evt.seekTime!),
],
]; ];
for (const [action, handler] of mediaActions) { for (const [action, handler] of mediaActions) {
@ -322,7 +307,7 @@ const useMediaSession = (
// ignored // ignored
} }
} }
}, [enabled, nativeRef, actions]); }, [enabled, nativeRef]);
useEffect(() => { useEffect(() => {
if (enabled) { if (enabled) {