0

I made this component to play an audio file when the page is rendered.

class Audio extends Component {

  randomTrack(){
        [...]
  }

  componentDidMount() {
    const audioEl = document.getElementsByClassName("audio-element")[0]
    audioEl.play()
  }

  render() {
      var trackname=this.randomTrack();
    return (
      <div>
        <audio className="audio-element">
          <source src={trackname}></source>
        </audio>
      </div>
    )
  }
}
export default Audio;

Each time the browser window reloads after saving changes in code, the audio plays.

BUT if I manually refresh the window OR if I deploy the code to a site and then open the site, it won't play. I get it has something to do with this error I then get in the console:

Audio.js:12 Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

But then, why does it play when it reloads? And is it possible to make it play automatically when the page loads, somehow?

Thanks in advance!

Liunai
  • 43
  • 6
  • check this https://stackoverflow.com/questions/49930680/how-to-handle-uncaught-in-promise-domexception-play-failed-because-the-use – Kavindu Vindika Sep 24 '21 at 22:13

1 Answers1

0

You can try it in this way

class Audio extends Component {

  randomTrack(){
        [...]
  }

  render() {
    let trackname=this.randomTrack();
    return (
      <div>
        <audio autoplay className="audio-element">
          <source src={trackname}></source>
        </audio>
      </div>
    )
  }
}
export default Audio;

a better way to use a standard solution to play audio.

Nico Peck
  • 538
  • 3
  • 16