简体   繁体   中英

Why audio didn't play's on click?

I am creating a drum machine app. I can't find a method to play audio on pressing a button so I tried it my self. I created a separate method that returns audio element with source of audio file. I call that method on clicking a button but I can't hear any audio. Here is the code:

 class App extends Component {
  constructor(props){
      super(props);
            this.clicker=this.clicker.bind(this);

 }
  clicker(){
  return(
    <audio autoplay>
    <source src="./1.mp3" type="audio/mpeg"/>
    </audio>
   )
 }

render() {
 return (
  <div className="App">
    <input type="button" onClick={this.clicker} value="play">
    </input>
  </div>
  );
  }
 }

is my approach correct to creating a drum machine or is there any better way? any further help will be appreciated.. Thanks..

You need to add your audio player to the DOM then call play on it, here is a quick example.

 class App extends Component { constructor(props){ super(props); this.clicker=this.clicker.bind(this); } } render() { return ( <div className="App"> <input type="button" onClick="document.getElementById('myAudioPlayer').play()" value="play"> </input> </div> <audio autoplay id="myAudioPlayer"> <source src="./1.mp3" type="audio/mpeg"/> </audio> ); } } 

Well after a little research and reading this HTML5 audio is not playing in my React app in localhost I get to know that you have to import mp3 files before using them as import mp3_file from {{filename}} . Then you can use them and it works.... Perfect!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM