diff --git a/app/components/Layout.tsx b/app/components/Layout.tsx index 3d11b58..54677c9 100644 --- a/app/components/Layout.tsx +++ b/app/components/Layout.tsx @@ -55,32 +55,12 @@ export function Layout({cart, children = null, header}: LayoutProps) { const sounds = ['/3.wav']; - const playRandomSound = () => { - const randomSound = sounds[Math.floor(Math.random() * sounds.length)]; - const sound = new Audio(randomSound); - sound.volume = 0.3; - sound.play(); - }; - - useEffect(() => { - let firstInteraction = true; - - window.addEventListener( - 'click', - (e) => { - if (firstInteraction) { - // Play initial sound to unlock audio on iOS - playRandomSound(); - // firstInteraction = false; - } - }, - // {once: true}, - ); - - return () => { - window.removeEventListener('click', playRandomSound); - }; - }, []); + // const playRandomSound = () => { + // const randomSound = sounds[Math.floor(Math.random() * sounds.length)]; + // const sound = new Audio(randomSound); + // sound.volume = 0.3; + // sound.play(); + // }; const handleUserInteraction = () => { setShowLogo(false); @@ -91,6 +71,63 @@ export function Layout({cart, children = null, header}: LayoutProps) { audio.play(); }; + let audioContext; + let soundBuffers = []; + + // Function to play a random sound + const playRandomSound = () => { + const soundIndex = Math.floor(Math.random() * soundBuffers.length); + const buffer = soundBuffers[soundIndex]; + if (buffer && audioContext) { + const source = audioContext.createBufferSource(); + source.buffer = buffer; + source.connect(audioContext.destination); + source.start(0); + } + }; + + // Function to load all sounds into buffer + const loadSounds = async (audioContext, soundFiles) => { + const bufferPromises = soundFiles.map(async (file) => { + const response = await fetch(file); + const arrayBuffer = await response.arrayBuffer(); + return audioContext.decodeAudioData(arrayBuffer); + }); + soundBuffers = await Promise.all(bufferPromises); + }; + + // Unlock audio context on the first interaction + const unlockAudio = () => { + // Create a new AudioContext + audioContext = new window.AudioContext(); + + // Load sounds + loadSounds(audioContext, sounds); + + // Play a silent sound to unlock the audio + const buffer = audioContext.createBuffer(1, 1, 22050); // an empty one-sample buffer + const source = audioContext.createBufferSource(); + source.buffer = buffer; + source.connect(audioContext.destination); + source.start(0); + + // Remove the event listener + window.removeEventListener('click', unlockAudio); + }; + + useEffect(() => { + // Add event listener on component mount + window.addEventListener('click', unlockAudio); + + // Add event listener for playing random sounds + window.addEventListener('click', playRandomSound); + + // Remove event listener on component unmount + return () => { + window.removeEventListener('click', playRandomSound); + }; + }, []); + return (