使用库:https://github.com/joshwcomeau/use-sound
IOS safari 下不能使用javascript调整音频的volume属性
可以使用库 use-sound来处理
播放背景音乐:
export const useCrashBgSound = () => {
const globalVolume = useAtomValue(gameVolumeState);
const [play, { sound: bgSound, pause, stop }] = useSound(
'/audios/crash/bg.mp3',
{
volume: globalVolume / 100,
loop: true,
interrupt: true,
},
);
const playCrashBg = () => {
// if (globalVolume === 0) {
// console.log('crash bg volume is 0 return');
// return;
// }
if (bgSound && bgSound.playing()) {
console.log('crash bg is playing return');
return;
} else {
play();
}
};
const isPageActive = usePageVisibility();
useEffect(() => {
if (isPageActive) {
playCrashBg();
} else {
pause();
}
}, [isPageActive]);
useEffect(() => {
return () => {
stop();
};
}, [bgSound]);
return {
playCrashBg: playCrashBg,
pauseCrashBg: pause,
};
};