在react-js中播放声音



我试着在react-js上播放声音,但我不能让它启动。我在reactClass中初始化了声音变量,在getinitialstate:

之前
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().

! !EDIT2:

我还注意到,如果我设置按钮,播放声音。如果我打开文件管理器,找到index。html,然后打开它,效果很好。如果我尝试从webpack-server: localhost:8000/app/index.html页面,它不会工作。得到相同的DOMException。为什么会这样?

经过一段时间的尝试,我做了2个按钮,一个开始的声音和一个停止,在我的index.html文件。所以我尝试了一下,我注意到它可以从我的文件管理器中工作,但如果我尝试从webpack服务器中工作则不行。所以我检查了我的路径,而不是"files/audio.mp3"我改成了"../files/audio.mp3"。这是新手犯的错误,但当你让Android开发人员在javascript中工作时就会发生这种情况:)))

最新更新