问题
I try to play a sound on react-js but I can't make it start. I have my sound var initialised in my reactClass, before get InitialState:
var App = React.createClass({
audio: new Audio('files/audio.mp3'),
getInitialState: function () {
return {
playSound: false,
........
}
}
And this are the functions that I have for start and stop:
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");
});
}
},
But I get back this answer:
react-app.js:346 Uncaught (in promise) DOMException: The element has no supported sources.
I have tried both with a .mp3 and .wav file. but it won't start. What am I doing wrong?
!!!! EDIT: Also tried adding a HTML item:
<audio id="beep" loop>
<source src="files/ring.wav" type="audio/wav" />
</audio>
And with the following start/stop:
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");
});
}
},
Then I get no error on start, but it doesn't start. When I press pause I get:
Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause().
!!!! EDIT2:
Also I noticed, that if I set buttons, to play the sound. If I open the file manager, go to my index.html and open it, it works perfectly. If I try the page from the webpack-server: localhost:8000/app/index.html, it won't work. getting the same DOMException. why is this?
回答1:
After trying for a while, I made 2 buttons, 1 to start the sound and one to stop, in my index.html file. So I tried that, and I noticed that it works from my file manager, but not if I try from the webpack server. So I checked my paths, and instead of: "files/audio.mp3" I changed it to "../files/audio.mp3". A rookie mistake, but that's what happens when you put a Android developer to work in javascript :)))
来源:https://stackoverflow.com/questions/39787533/play-sound-in-react-js