Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda