Skip to content

Commit

Permalink
fix(webview): improve stability of default volume
Browse files Browse the repository at this point in the history
  • Loading branch information
aidenlx committed Mar 18, 2024
1 parent 3341c66 commit 0edd851
Showing 1 changed file with 29 additions and 6 deletions.
35 changes: 29 additions & 6 deletions apps/app/src/components/hook/use-hash.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { MediaPlayerInstance } from "@vidstack/react";
import { useMediaPlayer } from "@vidstack/react";
import { debounce } from "obsidian";
import { useEffect, useRef } from "react";
import { useMediaViewStore, useSettings } from "../context";

Expand Down Expand Up @@ -30,11 +32,32 @@ export function useDefaultVolume() {
const initVolumeRef = useRef<number>(initVolume);
initVolumeRef.current = initVolume;

useEffect(
() =>
player?.subscribe(({ canPlay }) => {
if (canPlay) player.volume = initVolumeRef.current;
const locked = useRef(false);

useEffect(() => {
const unlock = debounce(
() => {
locked.current = false;
},
1e3,
true,
);
const updateVolume = (e: { target: MediaPlayerInstance }) => {
e.target.provider?.setVolume(initVolumeRef.current);
locked.current = true;
unlock();
};
if (!player) return;
const unloads = [
player.listen("can-play-through", updateVolume),
player.listen("can-play", updateVolume),
player.listen("loaded-data", updateVolume),
player.listen("loaded-metadata", updateVolume),
player.subscribe(({ volume }) => {
if (!locked.current || volume === initVolumeRef.current) return;
player.provider?.setVolume(initVolumeRef.current);
}),
[player],
);
];
return () => unloads.forEach((u) => u());
}, [player]);
}

0 comments on commit 0edd851

Please sign in to comment.