【问题标题】:Play sound in react-js在 react-js 中播放声音
【发布时间】:2016-09-30 22:49:31
【问题描述】:

我尝试在 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().

!!!! EDIT2:

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

【问题讨论】:

  • 我能问一下你从哪里调用 playSound() - 渲染或另一个 React 生命周期方法?
  • 嗯,它有点复杂。但是我有一个 react-app.js 类,它是主要的 index.html,并且有选项卡和一个用于呈现我的页面的视图。我初始化了一个具有回调函数的 C++ 库,当我在本机中更改内容时,我得到回调,并从那里播放声音。我解决了问题,这很简单,现在我想到了,我现在就添加响应

标签: javascript audio reactjs media wav


【解决方案1】:

尝试了一段时间后,我在 index.html 文件中制作了 2 个按钮,1 个用于启动声音,1 个用于停止。所以我尝试了,我注意到它可以在我的文件管理器中工作,但如果我从 webpack 服务器尝试则不行。 所以我检查了我的路径,而不是: “files/audio.mp3”我把它改成了“../files/audio.mp3”。一个菜鸟的错误,但是当你让 Android 开发人员使用 javascript 工作时会发生这种情况:)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    相关资源
    最近更新 更多