| Issue | Root Cause | Primary Fix |
|---|---|---|
| Audio Duration returns NaN | Accessing duration property before metadata is loaded. | Use the onLoadedMetadata event listener. |

What is React Audio Duration NaN?
The “React audio duration NaN” error occurs when a developer attempts to access the duration property of an HTML5 audio element before the browser has finished parsing the file’s metadata.
In React, this usually happens because the component renders and immediately tries to display the duration state, which defaults to NaN (Not a Number) until the audio file header is fully read.
This is a common synchronization issue. Because audio files are streamed, the length of the track is unknown until the loadedmetadata event fires. If you try to perform math or display this value too early, your UI will break.
Step-by-Step Solutions
1. Use the onLoadedMetadata Event
The most reliable way to fix this is to wait for the metadata to load. You can attach an event handler directly to the audio tag in React.
// Example of handling metadata in React
const AudioPlayer = () => {
const [duration, setDuration] = React.useState(0);
const handleMetadata = (e) => {
const seconds = e.currentTarget.duration;
if (!isNaN(seconds)) {
setDuration(seconds);
}
};
return (
<audio
onLoadedMetadata={handleMetadata}
src="your-audio-file.mp3"
controls
/>
);
};
2. Implement a ReadyState Check
If you are using useRef to access the audio element, you can check the readyState property. A value of 1 or higher indicates that metadata is available.
// Check if audio is ready
if (audioRef.current.readyState > 0) {
const total = audioRef.current.duration;
setDuration(total);
}
3. Formatting the Output
Since the duration might still be NaN for a split second during the initial render, always provide a fallback value in your JSX to prevent “NaN” from appearing to the user.
// Displaying a safe fallback
<p>Duration: {isNaN(duration) ? "00:00" : duration.toFixed(2)}</p>
4. Dealing with Dynamic Source Changes
If your audio source changes dynamically, the onLoadedMetadata event will fire again. Ensure your state updates correctly by resetting the duration to 0 whenever the src prop changes to avoid displaying the old duration for the new file.