【问题标题】:Audio play() not responding in create-react-app componentDidMount音频播放()在 create-react-app componentDidMount 中没有响应
【发布时间】:2018-04-22 11:49:55
【问题描述】:

我创建了一个 create-react-app 项目,我设法将 jquery 导入为 $ 并在 componentDidMount() 生命周期挂钩中使用 I,

在 render() 方法中我有

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

国家

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

我想在页面加载时调用音频文件播放 1.. 作为背景音乐,我尝试使用

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

但它接缝

play();

功能不正常

附:我把它当作游戏。另外,我有几个按钮可以在 onClick 上执行一个功能。如果你给我一个建议,我想知道如何在点击时播放声音。 谢谢。

【问题讨论】:

    标签: javascript html reactjs audio


    【解决方案1】:

    为了播放背景声音,不要使用componentDidMount()<audio> 允许我们以声明的方式使用这两个属性:

    • autoPlay: 歌曲会在挂载时播放。
    • loop:歌曲播放完毕后会循环播放。

    例子:

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

    【讨论】:

    • 虽然这段代码可以回答问题,但最好解释一下如何解决问题,并提供代码作为示例或参考。仅代码的答案可能会令人困惑且缺乏上下文。
    • 我刚刚编辑了我的答案给你一个更好的解释。
    【解决方案2】:

    尝试遵循这是我为另一个答案创建的代码 sn-p 可能会对您有所帮助。在此代码中,页面加载时会播放音频,您可以通过单击按钮来停止它

    //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()" />

    【讨论】:

    • @AkhilAravind 因为声音文件,使用它并替换为你的声音文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 2015-08-24
    • 2021-10-17
    • 2016-06-17
    • 1970-01-01
    相关资源
    最近更新 更多