In a NextJS app handling audio data I have the following issue getting the length of a sound file.
Here is the relevant code. Let me know if I do something wrong or if more information is needed.
const AudioPlayer = ({audio=''}: {audio?: string}) => {
const audioRef = useRef<HTMLAudioElement | null>(null);
const [duration, setDuration] = useState(0);
........
const handleLoad = () => {
console.log('-handleLoad(AudioPlayer)- CALLED !!!')
console.log('duration -> '+audioRef.current!.duration.toString())
setDuration(audioRef.current!.duration)
}; /* End of handleLoad */
........
return (
<div>
<main>
<audio src={audio}
ref={audioRef}
id="audio-player"
onPlay={handlePlay}
onEnded={handleEnd}
onLoadedMetadata={handleLoad} />
........
</main>
</div>
);
}; /* End of AudioPlayer */
export default AudioPlayer;
The problem I have is that I seem to get somewhat random value for the duration. I have seen several places on the net saying that the onLoadedMetadata event is the thing to use to catch the duration, but I get some weird results. Did I miss some details ?