Add Play and Pause Events to the Audio Player

Lindsey Kopacz
InstructorLindsey Kopacz
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 2 years ago

In this lesson, we will create event listeners for the play and pause events on an audio player element and use these listeners to update the value of a variable called isPlaying that tracks the current state of the player (e.g., whether it is currently playing or paused). The event listeners, named onPlay and onPause, will be triggered when the user presses the play or pause button on the audio player element itself, not on a custom play button that may have been created.

Instructor: [0:00] So far, what we have is working well, but we haven't mapped all of the audio elements states to the react app states. For example, when I press Play on the audio player, you'll notice that this state does not change. Let's go back to the MDN docs. [0:16] Down in the event section, we have the play event and the pause event. We can use the play event to set isPlaying to true, and we can use the pause event to set isPlaying to false.

[0:27] Back in the code, underneath onTimeUpdate, we'll type onPlay, and we'll just do a function in here, that's setIsPlayingToTrue. Then onPause we'll do the same thing and pass a function of setIsPlayingToFalse. Let's go back to the app, refresh. Now, if I press this Play button, the state will update.

[0:53] To summarize, we have just mapped the play and pause events to the react state. We added onPlay on the audio element and set isPlaying to true, and we took the pause and onPause on the audio element, we set isPlaying to false.

egghead
egghead
~ 31 seconds ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today