Skip to content

Commit

Permalink
Merge pull request #5 from ChisatoNishikigi73/music-1
Browse files Browse the repository at this point in the history
feat: Make bgm in and out more elegant
  • Loading branch information
Yue-plus authored Sep 29, 2024
2 parents e43e2ed + 2980ef7 commit 2a5845f
Showing 1 changed file with 39 additions and 4 deletions.
43 changes: 39 additions & 4 deletions src/components/header/NavTools.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,51 @@ export function Social() {

export function Sound() {
const [active, setActive] = useState(arknightsConfig?.bgm?.autoplay ?? false)
const [volume, setVolume] = useState(active ? 1 : 0)
const audioRef = useRef<HTMLAudioElement>(null)
const [isFading, setIsFading] = useState(false);
const fadeIntervalRef = useRef<number | null>(null);

useEffect(() => {
if (audioRef.current) {
if (active) audioRef.current.play().catch(e => console.error(e));
else audioRef.current.pause()
const audio = audioRef.current;

const handleFade = (targetVolume: number) => {
setIsFading(true);
if (fadeIntervalRef.current) clearInterval(fadeIntervalRef.current);

fadeIntervalRef.current = setInterval(() => {
if ((targetVolume === 1 && audio.volume < 1) || (targetVolume === 0 && audio.volume > 0)) {
audio.volume = Math.max(0, Math.min(1, audio.volume + (targetVolume === 1 ? 0.25 : -0.25)));
setVolume(audio.volume);
} else {
if (fadeIntervalRef.current) clearInterval(fadeIntervalRef.current);
setIsFading(false);
if (targetVolume === 0) audio.pause();
}
}, 100) as unknown as number;
};

if (active) {
audio.play().catch(e => console.error(e));
handleFade(1);
} else {
handleFade(0);
}
}

return () => {
if (fadeIntervalRef.current) clearInterval(fadeIntervalRef.current);
};
}, [active]);

const handleClick = () => {
if (!isFading) {
setActive(!active);
}
}, [active])
};

return <div className={BoxClassName} onClick={_ => setActive(!active)}>
return <div className={BoxClassName} onClick={handleClick}>
<IconSound className={SvgClassName} style={{
color: active ? ActiveColor : InactiveColor,
transition: "transform .3s",
Expand Down

0 comments on commit 2a5845f

Please sign in to comment.