Tracking Audio Playback Progress by Adding Elapsed Time

Lindsey Kopacz
InstructorLindsey Kopacz
Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we are creating a new state called mediaTime with an initial value of 0, updating sample text in the markup to display the value of mediaTime, and adding an event listener to the audio element for the timeUpdate event.

In the timeUpdate event listener callback function, the mediaTime state is set to the audio element's current time, which can be accessed using the audioRef.current.currentTime. A function is added to the onTimeUpdate event of the audio element, to be able to track the current time. And a time formatter is added to format the time for displaying elapsed time and total time.

Think about: How often does onTimeUpdate update? (every second, not every millisecond)

Lindsey Kopacz: [0:00] Now, let's add the mediaTime state. We're going to destructure mediaTime and setMediaTime. We are going to set the initial state to . Next in the elapsed time span, we are going to replace that to be mediaTime. [0:18] Before we do anything else, let's go back to MDN. Let's click on timeUpdate. We want to use this audio event to change the time and update the time. Whenever the currentTime attribute has been updated on the audio element, the timeUpdate event will run.

[0:36] Let's create a function here that's onTimeUpdate and create that arrow function. onTimeUpdate, we are going to setMediaTime to be the audioRef.current.currentTime.

[0:49] Now, let's add that function onto the onTimeUpdate event on the audio element. Let's press Play and see what happens to the elapsed time. Great. That's working really well.

[1:04] These times look kind of ugly. Let's format them. I'm just going to go to the syntax GitHub page and copy this formatTime function, so const formatTime, I'll make that look like an arrow function. Then in the elapsedTime and totalTimeSpans, I am going to wrap each of those states with the formatter. If I go back to the app, you'll see that it looks way better.

[1:32] To summarize, we created a mediaTime state, then we created an onTimeUpdate function that sets the mediaTime to the currentTime on the audioRef. Then we added the onTimeUpdate to the audio element and used that function. Then we created a time formatter and wrapped the duration and the mediaTime with those formatters.