Creating a Playback Rate Button

Lindsey Kopacz
InstructorLindsey Kopacz
Share this video with your friends

Social Share Links

Send Tweet

We are creating a playback rate button in a React application. An array of rates is created, and each element of the array is mapped to a button. Each button is given an onClick handler that calls an anonymous function called changeRate.

changeRate sets the playback rate of an audio element to the rate passed as an argument. When the button is pressed in the browser, it shows the new playback rate.

Think about: We have all these states for volume, media time etc, why don't we have one for rate?

[0:00] Now we're going to create a playback rate button. First, let's create an array called rates. And in that array, I'm just going to say .75, one, 1.5, and two. Underneath the rewind and fast forward buttons, we are going to map through those rates. That callback will take the rate and the index. And we will return button with an onClick handler, and we're going to pass it an anonymous function called changeRate. And we are going to pass that the rate. And inside the button, we are going to render the rate text and then an x. Don't forget in React when we're mapping through elements, we have to add a key. [0:45] We'll set that key to be the index. Now we have to create this function. Underneath the rates array, we're going to create that function. It's going to take an argument of rate. And inside that function, we are going to do audioRef.current.playBackRate equals rate. Now let's go back to the browser and see what that looks like. So if we press play, we will get the 1x playback rate because that's a default.

[1:12] But if we press 2x, you'll see that elapsed time is going way quicker. So to summarize, we created an array of rates with values ranging from .75 to 2. Then in the JSX, we mapped through those rates. Each rate has its own button that renders that rate. Then each button also has an onClick handler that we pass an anonymous function called changeRate.

[1:36] And changeRate takes the rate as an argument. In that function, changeRate, we set the audioRef.

[1:41] current.playBackRate to rate.