Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Audio not playing on render - React

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!