Skip to content

Commit

Permalink
fix: audio not loading on ios (freeCodeCamp#55993)
Browse files Browse the repository at this point in the history
  • Loading branch information
moT01 authored Sep 16, 2024
1 parent f463100 commit c00dfa1
Showing 1 changed file with 31 additions and 15 deletions.
46 changes: 31 additions & 15 deletions client/src/templates/Challenges/components/scene/scene.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ export function Scene({
const hasTimestamps = startTimestamp !== null && finishTimestamp !== null;
const audioTimestamp = hasTimestamps ? `#t=${startTimestamp}` : '';

const audioRef = useRef<HTMLAudioElement>(
new Audio(`${sounds}/${audio.filename}${audioTimestamp}`)
);
const audioRef = useRef<HTMLAudioElement>(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.
Expand All @@ -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}`);
Expand All @@ -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' };
Expand All @@ -93,7 +104,7 @@ export function Scene({
if (isPlaying) {
playScene();
} else {
finishScene();
resetScene();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isPlaying]);
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit c00dfa1

Please sign in to comment.