Replay audio every time a button is clicked - Javascript and HTML

Asked

Viewed 206 times

1

I want the audio to repeat from the beginning every time the button is pressed. Instead it only repeats after the audio has finished. (NOTE: I am using JSX)

Javascript

playShot() {
    var audio = document.getElementById('shot');
    audio.play();
}

HTML

<a onClick={() => this.playShot()} style={{zIndex: 5}} id="gat"><img src={gate2}/></a>

1 answer

4


Change the property currentTime of the element audio.

playShot() {
    let audio = document.getElementById('shot');
    audio.currentTime = 0
    audio.play(); // É opcional caso o play já esteja em execução.
}
  • It worked! Thanks friend, for the solution and also for the suggestion of Let. I am new in programming and have a lot to learn.

  • You say it’s optional if the play() is already running. Is there any way to verify this? Type the object áudio launches some event that ended the execution?

  • 1

    @Jeffersonquesado is possible to verify using the property audio.paused and at the end of the audio run, the player will launch an event for audio.onended()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.