Reputation: 1087
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
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