0

I'm trying to have a song play in the background of my app when it loads. However, it's not working with useEffect. I've also tried using useState in the useEffect with the same results. In the code below, if I click on the Play button, it works fine. Do you have any pointers on what I'm doing wrong?

First Attempt

const Footer = () => {
  let audio = new Audio(onlyYou);

  const start = () => {
    audio.play();
  };

  const stop = () => {
    audio.pause();
  }

  useEffect(() => {
    start()
  }, [])

  return (
    <footer>
      <div>
        <button onClick={start}>Play</button>
        <button onClick={stop}>Stop</button>
      </div>
    </footer>
   )

Second Attempt

const Footer = () => {
  const [playSong, setPlaySong] = useState(false);

  let audio = new Audio(onlyYou);

  const start = () => {
    audio.play();
  };

  const stop = () => {
    audio.pause();
  }

  useEffect(() => {
    setPlaySong(true)
  }, [])

  return (
    <footer>
      {playSong && start()}
      <div>
        <button onClick={start}>Play</button>
        <button onClick={stop}>Stop</button>
      </div>
    </footer>
   )
mfaccord
  • 225
  • 1
  • 3
  • 14

2 Answers2

1

Try this

const audio = new Audio(onlyYou)
const Footer = () => {
  useEffect(() => { audio.play() }, [])
  return (...)

to see if it works. This has to work first. Otherwise you might run into the problem that audio can't be started without user confirm problem.

How to make audio autoplay on chrome

windmaomao
  • 7,120
  • 2
  • 32
  • 36
  • Apparently it has something to do with autoplay and google chrome. Can't autoplay w/o user interaction. – mfaccord May 27 '21 at 21:11
1

It may have to do with the fact that the audio file is not loaded and is not ready to play when useEffect runs. Take a look here.

lgnstn
  • 11
  • 2
  • 1
    Apparently it has something to do with autoplay and google chrome. Can't autoplay w/o user interaction. – mfaccord May 27 '21 at 21:11