Files
personal/lib/useBgm.ts
T

59 lines
1.7 KiB
TypeScript

"use client";
import { useEffect, useRef } from "react";
/**
* Background music loader — port of the original effect (chunk
* 2689132c4e070b68.js): fetch /bgm.mp3 once, create a looping Audio at
* volume 0.35, play/pause with `enabled`. Keeps the same abort/cleanup
* semantics (revoke object URL on unmount).
*/
export function useBgm(enabled: boolean) {
const audioRef = useRef<HTMLAudioElement | null>(null);
const readyRef = useRef(false);
useEffect(() => {
let cancelled = false;
let objectUrl: string | null = null;
let audio: HTMLAudioElement | null = null;
readyRef.current = false;
fetch("/bgm.mp3")
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.blob();
})
.then((blob) => {
if (cancelled) return;
objectUrl = URL.createObjectURL(blob);
audio = new Audio(objectUrl);
audio.loop = true;
audio.volume = 0.35;
audioRef.current = audio;
readyRef.current = true;
if (enabled) void audio.play().catch(() => {});
})
.catch((err) => {
if (!cancelled) console.warn("Failed to load BGM:", err);
});
return () => {
cancelled = true;
if (audioRef.current === audio) audioRef.current = null;
audio?.pause();
audio?.removeAttribute("src");
audio?.load();
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
// Load once on mount (original: deps [enabled-guarded flag]).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const audio = audioRef.current;
if (!audio || !readyRef.current) return;
if (enabled) void audio.play().catch(() => {});
else audio.pause();
}, [enabled]);
}