k10a
k10a

Reputation: 1087

audio.pause() is not working after audio.play() in React

I would like to make it so that if I press again after playing an audio, it will stop. However, audio.pause() is not responding. Also, I tried to use useCallback, but that didn't work either.

const [played, setPlayed] = useState(false)

const audio = new Audio(src)

const playMessage = () => {
  setPlayed(!played)
  if (played) {
    audio.pause()
    audio.currentTime = 0
  } else {
    audio.play()
  }
}

Upvotes: 0

Views: 469

Answers (1)

invisal
invisal

Reputation: 11181

I think you create new audio object every time you re-render. Can you try

const audio = useMemo(() => new Audio(src), [src]);

Upvotes: 1

Related Questions