【发布时间】: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