Skip to content
Advertisement

create simple player with HTMLAudioElement in reactjs

I am create web application a simple player. I want to get the current time of the music that is playing.
this is log in useEffect and is great.

JavaScript

problem
when set e.target.currentTime in state .Music playback stops.

JavaScript


CodeSandbox

Advertisement

Answer

it will work with a local Audio element:

JavaScript

EDIT: to answer to OP why it doesn’t work in the initial variant

the application contains a foreign element, not controlled by React, so it should be kept in sync manually. Here, when calling setCurrentTime the component is reevaluated, so the reassignment of Audio.src should be prevented to not reset the audio. Also the event listener should be remover correctly to prevent memory leaks. (in fact while the code with a local Audio element is working, it is not perfect, and pressing on play during playback new Audio elements will be created and will play concomitantly). Below are the changes for a working variant with a global Audio element.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement