From 105afefa9461bb0c799c3a69efdcf386c3ec4cd1 Mon Sep 17 00:00:00 2001 From: Greg Rickaby Date: Tue, 13 Feb 2024 09:30:32 -0600 Subject: [PATCH] pause video if user starts another video --- components/HlsPlayer.tsx | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/components/HlsPlayer.tsx b/components/HlsPlayer.tsx index 2f67f68..426cc18 100644 --- a/components/HlsPlayer.tsx +++ b/components/HlsPlayer.tsx @@ -35,6 +35,42 @@ export default function HlsPlayer(props: HlsPlayerProps) { } }, [props.src, videoRef]) + /** + * Pause this video if another starts playing. + */ + useEffect(() => { + const video = videoRef.current + + // Dispatch a custom event whenever a video starts playing. + const playHandler = () => { + window.dispatchEvent(new CustomEvent('videoPlayed', {detail: {video}})) + } + + if (video) { + // Listen for native event. + video.addEventListener('play', playHandler) + + // Set up the custom event. + const pauseIfNotCurrent = (event: Event) => { + const customEvent = event as CustomEvent<{video: HTMLVideoElement}> + + // Pause this video if another starts playing. + if (customEvent.detail.video !== video) { + video.pause() + } + } + + // Add the event listener. + window.addEventListener('videoPlayed', pauseIfNotCurrent) + + // Clean up the event listeners. + return () => { + video.removeEventListener('play', playHandler) + window.removeEventListener('videoPlayed', pauseIfNotCurrent) + } + } + }, []) + return (