Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda