Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useMediaVideoPlayback.ts

56 lines2.4 KB

1import { useIsFocused } from "@react-navigation/native";
2import { useEvent } from "expo";
3import type { VideoPlayer } from "expo-video";
4import { useCallback, useEffect, useRef } from "react";
5import { AppState } from "react-native";
6​
7import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "./videoAudioSession";
8​
9export function useMediaVideoPlayback(
10 player: VideoPlayer,
11 options: { readonly paused: boolean; readonly visible?: boolean },
12 playback: { play(): Promise<void>; pause(): void },
13) {
14 const focused = useIsFocused();
15 const fullscreenVideoOpen = useFullscreenVideoOpen();
16 const paused = options.paused || fullscreenVideoOpen || options.visible === false;
17 const active = useRef(focused && !paused && AppState.currentState === "active");
18 const fullscreen = useRef(false);
19 const interruption = useRef(0);
20 const { isPlaying } = useEvent(player, "playingChange", { isPlaying: player.playing });
21 useMediaAudioSessionHold(isPlaying);
22​
23 useEffect(() => {
24 active.current = focused && !paused && AppState.currentState === "active";
25 if (!active.current) interruption.current += 1;
26 if (!focused || paused || (!active.current && !fullscreen.current)) playback.pause();
27 // Native background handling distinguishes Android's fullscreen activity
28 // from leaving the app; React Native reports both as background.
29 const subscription = AppState.addEventListener("change", (state) => {
30 active.current = focused && !paused && state === "active";
31 if (!active.current) interruption.current += 1;
32 if (state === "inactive" || (state === "background" && !fullscreen.current)) playback.pause();
33 });
34 return () => subscription.remove();
35 }, [focused, playback, paused]);
36​
37 const createPlayRequest = useCallback(() => {
38 const requestedAt = interruption.current;
39 const requestedWhileActive = active.current;
40 // Returning to the content must not revive playback interrupted during loading.
41 return () => {
42 if (requestedWhileActive && active.current && requestedAt === interruption.current)
43 return playback.play();
44 };
45 }, [playback]);
46​
47 const onFullscreenEnter = useCallback(() => {
48 fullscreen.current = true;
49 }, []);
50 const onFullscreenExit = useCallback(() => {
51 fullscreen.current = false;
52 if (!active.current) playback.pause();
53 }, [playback]);
54​
55 return { active, fullscreen, createPlayRequest, onFullscreenEnter, onFullscreenExit };