Created
July 26, 2023 14:55
-
-
Save moretti/009459d103102b8d7f5535efc5fcd53d to your computer and use it in GitHub Desktop.
Vidstack Media Sync
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useMediaRemote } from '@vidstack/react'; | |
import { FunctionComponent, useEffect } from 'react'; | |
import { useMediaSyncContext } from './MediaSyncContext'; | |
// Workaround until https://github.com/vidstack/player/issues/756 is fixed. | |
// Re-implements the single playback functionality, so that only one video | |
// can play at any given moment | |
const MediaSync: FunctionComponent = () => { | |
const mediaRemote = useMediaRemote(); | |
const { mediaRemotes } = useMediaSyncContext(); | |
useEffect(() => { | |
const player = mediaRemote.getPlayer(); | |
if (!player) { | |
return; | |
} | |
mediaRemotes.add(mediaRemote); | |
function onPlay() { | |
mediaRemotes.forEach((otherRemote) => { | |
if (mediaRemote !== otherRemote) { | |
otherRemote.pause(); | |
} | |
}); | |
} | |
function onDestroy() { | |
mediaRemotes.delete(mediaRemote); | |
if (player) { | |
player.removeEventListener('play', onPlay); | |
} | |
} | |
player.addEventListener('play', onPlay); | |
return () => { | |
player.removeEventListener('play', onPlay); | |
player.removeEventListener('destroy', onDestroy); | |
}; | |
}, [mediaRemote, mediaRemotes]); | |
return null; | |
}; | |
export default MediaSync; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { FunctionComponent, createContext, useContext } from 'react'; | |
import type { MediaRemoteControl } from 'vidstack'; | |
export type MediaContextType = { | |
mediaRemotes: Set<MediaRemoteControl>; | |
}; | |
const MediaSyncContext = createContext<MediaContextType>({ | |
mediaRemotes: new Set<MediaRemoteControl>(), | |
}); | |
export const MediaSyncProvider: FunctionComponent = ({ children }) => { | |
return ( | |
<MediaSyncContext.Provider | |
value={{ mediaRemotes: new Set<MediaRemoteControl>() }} | |
> | |
{children} | |
</MediaSyncContext.Provider> | |
); | |
}; | |
export function useMediaSyncContext(): MediaContextType { | |
return useContext(MediaSyncContext); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment