From 956ad63e7fcf559e4d5b3cda08291c9ac8da0e6a Mon Sep 17 00:00:00 2001 From: san Date: Sat, 26 Oct 2024 22:32:08 +0530 Subject: [PATCH] add background music --- app/src/components/MusicPlayer.tsx | 52 ++++++++++++++++++++++++++++ app/src/components/Scene.tsx | 14 ++++++-- app/src/styles/Background.module.css | 12 +++++++ 3 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 app/src/components/MusicPlayer.tsx diff --git a/app/src/components/MusicPlayer.tsx b/app/src/components/MusicPlayer.tsx new file mode 100644 index 0000000..b54ed6e --- /dev/null +++ b/app/src/components/MusicPlayer.tsx @@ -0,0 +1,52 @@ +import { useState, useEffect, useRef, useCallback } from 'react'; +import styles from '../styles/Background.module.css'; + +const MusicPlayer = ({ onReady }: { onReady: (unmute: () => void) => void }) => { + const [isMuted, setIsMuted] = useState(false); + const audioRef = useRef(null); + + const play = useCallback(() => { + if (audioRef.current) { + audioRef.current.play().catch(error => console.log("Audio play failed:", error)); + } + }, []); + + const unmute = useCallback(() => { + if (audioRef.current) { + audioRef.current.muted = false; + setIsMuted(false); + play(); + } + }, [play]); + + useEffect(() => { + if (audioRef.current) { + audioRef.current.volume = 0.5; + audioRef.current.loop = true; + audioRef.current.muted = true; + play(); + onReady(unmute); + } + }, [play, onReady, unmute]); + + const toggleMute = () => { + if (audioRef.current) { + audioRef.current.muted = !isMuted; + setIsMuted(!isMuted); + if (!isMuted) { + play(); + } + } + }; + + return ( + <> +