Since Chrome 50, a play()
call on audio
(or video
) element returns Promise
instance (further details can be found in this reference). You should add detection for successful play and the Promise
instance is fulfilled like this example:
HTML
<audio id="song" src="../path/to/audio/file.mp3" />
<button id="play">Play</button>
JS
var play = $('#play'); // example
play.click(function (e) {
e.preventDefault();
var playback = document.querySelector('#song').play();
if (playback !== undefined) {
playback.then(function() {
// do something
}).catch(function(error) {
// do something else
});
}
});
Another example can be found in HTMLMediaElement.play() Returns a Promise Sample.
If it turns to be CORS issue, try to set crossorigin
attribute as anonymous one, then ensure that response header returned from server contains Access-Control-Allow-Origin: *
:
var song = document.getElementById('song');
song.setAttribute('crossorigin', 'anonymous');
// or this:
song.crossOrigin = 'anonymous';
Related issue:
DOMException: Failed to load because no supported source was found