Audio play() not responding in create-react-app componentDidMount

I created a create-react-app project I manage to import jquery as $ and use I in the componentDidMount() lifecycle hook,

In the render() method I have

audio ref="bgAudio"
   source src={this.state.bgAudio} 

the state

this.state{ bgAudio:"./bgAudio.mp3" }

I want to invoke the audio file to play 1 when the page loaded .. as a background music, I tried using

componentDidMount(){
 this.refs.bgAudio.play();
}

but it seams the

play();

function is not working

P.S. I'm making it as a game. Also, i have a few buttons that onClick execute a function .. I would like if you give me an advice how to play sounds on click as well. Thank you.

Upvotes: 2

Views: 1755

Answers (2)

Isaac Ferreira
Isaac Ferreira

Reputation: 436

In order to play a background sound, you don't to use componentDidMount(). <audio> allow us to do it in declarative way, using these both attributes:

  • autoPlay: the song will play when mounted.
  • loop: the song will loop when finished.

Example:

class App extends React.Component {
    render () {
        return (
            <div>
                <audio src={ audioURL } loop autoPlay />
            </div>
        )
    }
}

Upvotes: 1

Nisal Edu
Nisal Edu

Reputation: 7591

try following this is a code snippet I create for another answer might help you. In this code audio plays when page loaded you can stop it by clicking a button

//music
var audio = new Audio('http://www.sousound.com/music/healing/healing_01.mp3')
checksound();



function checksound() {

var myElement = document.getElementById("soundMenu");
  myElement.innerHTML = "Turn Sound " + (audio.paused ? "OFF" : "ON");

  if (audio.paused) {
    audio.play();
  } else {
    audio.pause();
  }

}

function myFunction() {


var myElement = document.getElementById("soundMenu");
  myElement.innerHTML = "Turn Sound " + (audio.paused ? "OFF" : "ON");

  if (audio.paused) {
    audio.play();
  } else {
    audio.pause();
  }
}
<button id="soundMenu" onclick="checksound()">Play</button>
<input type="text" onkeypress="myFunction()" />

Upvotes: 0

Related Questions