Implementing a Duration State

Lindsey Kopacz
InstructorLindsey Kopacz
Share this video with your friends

Social Share Links

Send Tweet

We created a duration state with an initial value of zero, then added an event listener to the audio element for the loadedMetaData event. In the event listener callback function, you set the duration state's value to be the audio element's current duration. This ensures that the value of the duration state is only set once the audio element metadata is loaded, allowing you to display the accurate total time of the audio file.

Think about: Why do we need to set the duration on the onLoadedMetadata event?

"The onLoadedMetadata event occurs when metadata for the specified audio/video has been loaded." You can read the docs here

[0:00] So the next thing we're going to do is create a duration state. So we're going to set a state as duration and then the setter is set duration and that initial state is going to be zero. Next, let's go to the markup and underneath the button we are going to create two spans. Each of them are going to have their own class name and in the first one we are going to set that class name as lapsed. In the next one we're going to set the class name to duration. Inside the first span we are going to create some sample text and we're going to say elapsed time and we're going to just set that at zero for now. In the duration span we are going to type total time and we are going to render the duration state. Before we do anything to set the duration let's go back to the MDN docs and click on the loaded metadata event. So what it says here is the loaded metadata event is fired when the metadata has been loaded. That doesn't mean much now but let's go back to the app and refresh. When I refresh I want you to keep an eye on the audio element and particularly where the duration is. So you might see for a very brief period it is at zero and then when the metadata is loaded it is 25.58. So to set the duration we have to wait until that metadata is loaded before we can set the duration. So let's create an onloaded metadata function. And then inside that arrow function we are going to set the duration to be audioRef current duration. And then on the audio element we're going to do onloaded metadata and add that function. So now let's go back to our app to refresh. [1:52] You'll see that our total time is about 1500 seconds. So to summarize we created the duration state and set the initial state to zero. Then we created an onloaded metadata function and set the duration to the audioRef.current.duration. Then on the audio element we added the onloaded metadata event and set that to that function.