Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(fuselage): AudioPlayer: Infinity duration audio files crashing #1159

Merged
merged 2 commits into from
Sep 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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