mirror of
https://github.com/movie-web/native-app.git
synced 2025-09-13 18:13:25 +00:00
refactor: make audiotrack stuff its own hook
This commit is contained in:
51
apps/expo/src/hooks/player/useAudioTrack.ts
Normal file
51
apps/expo/src/hooks/player/useAudioTrack.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { Audio } from "expo-av";
|
||||
|
||||
import type { Stream } from "@movie-web/provider-utils";
|
||||
|
||||
import type { AudioTrack } from "~/components/player/AudioTrackSelector";
|
||||
import { usePlayerStore } from "~/stores/player/store";
|
||||
|
||||
export const useAudioTrack = () => {
|
||||
const videoRef = usePlayerStore((state) => state.videoRef);
|
||||
const [audioObject, setAudioObject] = useState<Audio.Sound | null>(null);
|
||||
|
||||
const synchronizePlayback = useCallback(
|
||||
async (selectedAudioTrack?: AudioTrack, stream?: Stream) => {
|
||||
if (selectedAudioTrack && stream) {
|
||||
const { uri } = selectedAudioTrack;
|
||||
const sound = new Audio.Sound();
|
||||
await sound.loadAsync({
|
||||
uri,
|
||||
headers: {
|
||||
...stream.headers,
|
||||
...stream.preferredHeaders,
|
||||
},
|
||||
});
|
||||
setAudioObject(sound);
|
||||
} else {
|
||||
if (audioObject) {
|
||||
await audioObject.unloadAsync();
|
||||
setAudioObject(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (videoRef?.getStatusAsync && audioObject) {
|
||||
const videoStatus = await videoRef.getStatusAsync();
|
||||
|
||||
if (selectedAudioTrack && videoStatus.isLoaded) {
|
||||
await videoRef.setIsMutedAsync(true);
|
||||
await audioObject.setPositionAsync(videoStatus.positionMillis);
|
||||
await audioObject.playAsync();
|
||||
} else {
|
||||
await videoRef.setIsMutedAsync(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[videoRef, audioObject],
|
||||
);
|
||||
|
||||
return {
|
||||
synchronizePlayback,
|
||||
} as const;
|
||||
};
|
Reference in New Issue
Block a user