From c00dfa13e17cde845bef54b76c01670c3b6f17e9 Mon Sep 17 00:00:00 2001 From: Tom <20648924+moT01@users.noreply.github.com> Date: Mon, 16 Sep 2024 03:10:45 -0500 Subject: [PATCH] fix: audio not loading on ios (#55993) --- .../Challenges/components/scene/scene.tsx | 46 +++++++++++++------ 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/client/src/templates/Challenges/components/scene/scene.tsx b/client/src/templates/Challenges/components/scene/scene.tsx index 79fd884c725f67..b62148d718e4e3 100644 --- a/client/src/templates/Challenges/components/scene/scene.tsx +++ b/client/src/templates/Challenges/components/scene/scene.tsx @@ -34,9 +34,7 @@ export function Scene({ const hasTimestamps = startTimestamp !== null && finishTimestamp !== null; const audioTimestamp = hasTimestamps ? `#t=${startTimestamp}` : ''; - const audioRef = useRef( - new Audio(`${sounds}/${audio.filename}${audioTimestamp}`) - ); + const audioRef = useRef(new Audio()); // if there are timestamps, we use the difference between them as the duration // if not, we assume we're playing the whole audio file. @@ -46,7 +44,13 @@ export function Scene({ // on mount useEffect(() => { - audioRef.current.addEventListener('canplaythrough', audioLoaded); + const { current } = audioRef; + + if (current) { + current.addEventListener('canplaythrough', audioLoaded); + current.src = `${sounds}/${audio.filename}${audioTimestamp}`; + current.load(); + } // preload images loadImage(`${backgrounds}/${setup.background}`); @@ -64,13 +68,20 @@ export function Scene({ // on unmount return () => { - const { current } = audioRef; - - current.pause(); - current.currentTime = 0; - current.removeEventListener('canplaythrough', audioLoaded); + if (current) { + current.pause(); + current.currentTime = 0; + current.removeEventListener('canplaythrough', audioLoaded); + } }; - }, [audioRef, setup.background, setup.characters, commands]); + }, [ + audioRef, + audio.filename, + audioTimestamp, + setup.background, + setup.characters, + commands + ]); const initBackground = setup.background; const initDialogue = { label: '', text: '', align: 'left' }; @@ -93,7 +104,7 @@ export function Scene({ if (isPlaying) { playScene(); } else { - finishScene(); + resetScene(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isPlaying]); @@ -195,10 +206,15 @@ export function Scene({ }); }; - const finishScene = () => { - audioRef.current.pause(); - audioRef.current.src = `${sounds}/${audio.filename}${audioTimestamp}`; - audioRef.current.currentTime = audio.startTimestamp || 0; + const resetScene = () => { + const { current } = audioRef; + if (current) { + current.pause(); + current.src = `${sounds}/${audio.filename}${audioTimestamp}`; + current.load(); + current.currentTime = audio.startTimestamp || 0; + } + setShowDialogue(false); setDialogue(initDialogue); setCharacters(initCharacters);