|
| 1 | +"use client"; |
| 2 | +import React, { |
| 3 | + createContext, |
| 4 | + useContext, |
| 5 | + useEffect, |
| 6 | + useState, |
| 7 | + useRef, |
| 8 | +} from "react"; |
| 9 | + |
| 10 | + |
| 11 | +interface AudioContextType { |
| 12 | + musicVolume: number; |
| 13 | + setMusicVolume: (value: number) => void; |
| 14 | + sfxVolume: number; |
| 15 | + setSfxVolume: (value: number) => void; |
| 16 | + playBackgroundAudio: () => void; |
| 17 | + pauseBackgroundAudio: () => void; |
| 18 | + playAudioEffect: (src: string) => void; |
| 19 | + playingBackgroundAudio: boolean; |
| 20 | +} |
| 21 | + |
| 22 | +const AudioContext = createContext<AudioContextType | undefined>(undefined); |
| 23 | + |
| 24 | +export const useAudioCustom = () => { |
| 25 | + const context = useContext(AudioContext); |
| 26 | + if (!context) { |
| 27 | + throw new Error("useAudio must be used within a AudioProvider"); |
| 28 | + } |
| 29 | + return context; |
| 30 | +}; |
| 31 | + |
| 32 | +export const AudioProvider: React.FC<{ children: React.ReactNode }> = ({ |
| 33 | + children, |
| 34 | +}) => { |
| 35 | + const [musicVolume, setMusicVolume] = useState(0.3); // music volume 30% |
| 36 | + const [sfxVolume, setSfxVolume] = useState(1.0); // audio effect volume 100% |
| 37 | + const backgroundAudioRef = useRef<HTMLAudioElement | null>(null); |
| 38 | + |
| 39 | + const [playingBackgroundAudio, setplayingBackgroundAudio] = useState(false); |
| 40 | + |
| 41 | + useEffect(() => { |
| 42 | + backgroundAudioRef.current = new Audio("./assets/music/bg.mp3"); |
| 43 | + backgroundAudioRef.current.loop = true; |
| 44 | + backgroundAudioRef.current.volume = musicVolume; |
| 45 | + }, []); |
| 46 | + |
| 47 | + useEffect(() => { |
| 48 | + if (backgroundAudioRef.current) { |
| 49 | + backgroundAudioRef.current.volume = musicVolume; |
| 50 | + } |
| 51 | + }, [musicVolume]); |
| 52 | + |
| 53 | + const playBackgroundAudio = () => { |
| 54 | + setplayingBackgroundAudio(true); |
| 55 | + backgroundAudioRef.current |
| 56 | + ?.play() |
| 57 | + .catch((error) => |
| 58 | + console.error("Error playing background music:", error) |
| 59 | + ); |
| 60 | + }; |
| 61 | + |
| 62 | + const pauseBackgroundAudio = () => { |
| 63 | + setplayingBackgroundAudio(false); |
| 64 | + backgroundAudioRef.current?.pause(); |
| 65 | + }; |
| 66 | + |
| 67 | + const playAudioEffect = (src: string) => { |
| 68 | + const audioEffect = new Audio(src); |
| 69 | + audioEffect.volume = sfxVolume; |
| 70 | + audioEffect.play(); |
| 71 | + }; |
| 72 | + |
| 73 | + return ( |
| 74 | + <AudioContext.Provider |
| 75 | + value={{ |
| 76 | + musicVolume, |
| 77 | + setMusicVolume, |
| 78 | + sfxVolume, |
| 79 | + setSfxVolume, |
| 80 | + playBackgroundAudio, |
| 81 | + pauseBackgroundAudio, |
| 82 | + playAudioEffect, |
| 83 | + playingBackgroundAudio, |
| 84 | + }} |
| 85 | + > |
| 86 | + {children} |
| 87 | + </AudioContext.Provider> |
| 88 | + ); |
| 89 | +}; |
0 commit comments