Skip to content

Commit

Permalink
fix(fuselage): AudioPlayer: Infinity duration audio files crashing (
Browse files Browse the repository at this point in the history
#1159)

Co-authored-by: Douglas Fabris <[email protected]>
  • Loading branch information
yash-rajpal and dougfabris authored Sep 11, 2023
1 parent 56bc7a6 commit 385170c
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions packages/fuselage/src/components/AudioPlayer/AudioPlayer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,32 @@ function forceDownload(url: string, fileName?: string) {
xhr.send();
}

const getDurationForInfinityDurationAudioFile = (
src: string,
callback: (duration: number) => void
) => {
const audioElement = new Audio();
audioElement.src = src;

audioElement.addEventListener('loadedmetadata', () => {
const { duration } = audioElement;
if (duration === Infinity) {
audioElement.currentTime = 1e101;
return;
}

return callback(duration);
});

audioElement.addEventListener('durationchange', () => {
if (audioElement.duration === Infinity) {
return;
}
callback(audioElement.duration);
audioElement.remove();
});
};

export const AudioPlayer = forwardRef<
HTMLAudioElement,
{
Expand Down Expand Up @@ -169,8 +195,14 @@ export const AudioPlayer = forwardRef<
onTimeUpdate={(e) => {
setCurrentTime((e.target as HTMLAudioElement).currentTime);
}}
onLoadedData={(e) => {
setDurationTime((e.target as HTMLAudioElement).duration);
onLoadedMetadata={(e) => {
const { duration } = e.target as HTMLAudioElement;

if (duration !== Infinity) {
return setDurationTime(duration);
}

getDurationForInfinityDurationAudioFile(src, setDurationTime);
}}
onEnded={() => setIsPlaying(false)}
ref={refs}
Expand Down

0 comments on commit 385170c

Please sign in to comment.