我尝试在 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。为什么是这样?