Creating a Toggle for Playing and Pausing the Audio

Lindsey Kopacz
InstructorLindsey Kopacz
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 2 years ago

We Introduce MDN Media docs and all the APIs.

In this lesson, we added the useRef and created an audioRef in our components. We also added the ref to the audio element to control it outside of the audio element. We use the useState hook, and we created an isPlaying state. And finally, we added a button that dynamically renders the text as pause and play depending on the isPlaying state. On click of that button, we toggle the isPlaying state, and depending on that state, we either pause or play it.

[0:00] Before we start making our custom audio player, I want to introduce you to the MDN docs for this HTML media element. This API contains all of the items we need to make a custom audio player. You'll see properties such as muted, paused, playback rate, duration. You'll also see methods like pause and play. You'll also see events such as loaded metadata and ended and play and pause. We can use this API to control our media element. To get started, we need to add useRef from React. And then we're going to create an audioRef and useRef and we're going to set that value to . So now that we have this audioRef, let's add that to our audio element. [0:48] Now we're going to import useState because we want to create a toggle playing state. So let's see structure isPlaying, which is the state, and set isPlaying, which is the setter. And we'll set that initial value to . So now we can start building out our custom audio player. Above the audio element, let's create a div. And inside that div, let's create a button. Inside the button, we will create a ternary that says if isPlaying. Then we'll render pause.

[1:22] Else, we'll render play.

[1:25] We need to add an onClick event that toggles that state. So we'll call that togglePlaying. We'll create that function. So const togglePlaying and we'll create an arrow function. So first thing we'll do is we'll set isPlaying to the opposite of isPlaying. And now this is where that media API comes in handy. We'll do another ternary that says isPlaying audioRef current pause.

[1:56] Else audioRef current play. So we're using the play and pause method that we just went over. Now let's check to make sure it worked. We press play.

[2:11] You'll also notice that play text changed to pause when we were playing. So to summarize, we added the useRef and created an audioRef. We added the ref to the audio element so that we could control it outside of the audio element. We added the useState hook and we created an isPlaying state. And then we added a button that dynamically renders the text as pause and play depending on the isPlaying state. And then on click of that button, we toggle the isPlaying state. And depending on that state, we either pause or play it.