U
U
uRoot2020-12-17 12:43:13
React
uRoot, 2020-12-17 12:43:13

How to play audio in React after page load?

I need to automatically play audio using JS when rendering a component. This is exactly what is needed, because the track itself is processed in JS. I try like this:

function onPlay(audioRef) {
     ...
     audioRef.current.play()
  }

 ...

  useEffect(() => {
    return onPlay(audioRef)
  }, [])

  return(
    <audio
      ref={audioRef}
      loop
      src={sound}>
    </audio>
  )


But I get an error:
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
How to properly play audio on the machine without user intervention?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Makarov, 2020-12-17
@kirbi1996

It is not entirely clear that in your case audioRef, you will transfer it to a function, but where it is initialized for you is not clear. Try to create maybe a normal state in useEffect to translate it into true, and already see what happens next. Well, this is fine if you are expecting a boolean value, although you can do setState of any type there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question