Skip to content

Commit

Permalink
pause video if user starts another video
Browse files Browse the repository at this point in the history
  • Loading branch information
gregrickaby committed Feb 13, 2024
1 parent b38d7b7 commit 105afef
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions components/HlsPlayer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<video
autoPlay={props.autoPlay}
Expand All @@ -43,6 +79,7 @@ export default function HlsPlayer(props: HlsPlayerProps) {
crossOrigin={props.crossOrigin}
data-hint={props.dataHint}
height={props.height}
id={props.id}
loop={props.loop}
muted={props.muted}
playsInline={props.playsInline}
Expand Down

0 comments on commit 105afef

Please sign in to comment.