小编典典

在react-js中播放声音

reactjs

我尝试在react-js上播放声音,但无法启动。在获取InitialState之前,我已在我的reactClass中初始化了声音变量:

var App = React.createClass({
audio: new Audio('files/audio.mp3'),
getInitialState: function () {
return {
  playSound: false,
   ........
 }
}

这是我用于启动和停止的功能:

   playSound: function() {
if(!this.state.playSound){
    this.setState({
        playSound: true,
    }, function(){
      console.log("play sound 1");
      this.audio.play();
      console.log("play sound 2");
    });
}
},

stopSound: function() {
if(this.state.playSound){
    this.setState({
        playSound: false,
    }, function(){
        console.log("stop sound 1");
        this.audio.pause();
        console.log("stop sound 2");
    });
}
},

但是我得到了这个答案:

react-app.js:346 Uncaught (in promise) DOMException: The element has no supported sources.

我已经尝试过同时使用.mp3和.wav文件。但它不会开始。我究竟做错了什么?

!!!! 编辑:还尝试添加HTML项:

  <audio id="beep" loop>
         <source src="files/ring.wav" type="audio/wav" />
      </audio>

并使用以下开始/停止:

  playSound: function() {
if(!this.state.playSound){
    this.setState({
        playSound: true,
    }, function(){
      console.log("play sound 1");
      var audioElement = document.getElementById('beep');
      audioElement.setAttribute("preload", "auto");
      audioElement.autobuffer = true;
      audioElement.load();
      audioElement.play();
      console.log("play sound 2");
    });
}
},

stopSound: function() {
if(this.state.playSound){
    this.setState({
        playSound: false,
    }, function(){
        console.log("stop sound 1");
        var audioElement = document.getElementById('beep');
        audioElement.pause();
        console.log("stop sound 2");
    });
}
},

然后我在启动时没有错误,但是没有启动。当我按下暂停时,我得到:

Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause().

!!!! 编辑2:

我还注意到,如果设置按钮,则可以播放声音。如果我打开文件管理器,请转到index.html并将其打开,即可正常运行。如果我从webpack-
server尝试页面:localhost:8000 / app /
index.html,它将无法正常工作。得到相同的DOMException。为什么是这样?


阅读 1454

收藏
2020-07-22

共1个答案

小编典典

尝试了一段时间之后,我在index.html文件中做了2个按钮,其中1个用于开始声音,一个用于停止声音。因此,我尝试了这一点,但我注意到它可以从文件管理器中使用,但如果从webpack服务器中尝试则不能。因此,我检查了路径,而不是:“
files / audio.mp3”改为“
../files/audio.mp3”。一个菜鸟错误,但这就是当您让一个Android开发人员在javascript中工作时会发生的事情:)))

2020-07-22