简体   繁体   English

为什么点击时没有播放音频?

[英]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. 您需要将音频播放器添加到DOM,然后在其上调用play,这是一个简单的示例。

 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}} . 经过一番研究并阅读了HTML5音频后,我在本地主机的React应用程序中没有播放音频,我知道您必须先导入mp3文件,然后才能将它们用作来自{{filename}}的import mp3_file Then you can use them and it works.... Perfect!! 然后您就可以使用它们了,它就可以工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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