I am trying to play audio automatically based on condition when I get ajax response. I receive response.code == 1
from my ajax call, but it does not play the audio.
<audio id="myAudio" >
<source src="{{asset('Dashboard/alarm.mp3')}}" type="audio/mpeg">
</audio>
$.ajax({
url: '{{url('/')}}',
type: 'POST',
data: {
_token: _token
},
dataType: 'json',
success: function(response) {
if (response.code == 1) {
playAudio();
}
}
});
function playAudio() {
var x = document.getElementById("myAudio");
x.play();
}
2
Answers
Browsers are often blocking sounds that are not triggered by user interaction, you can start playing the audio on the mouse move for example:
As @imvain2 mention is the comment, browsers won’t allow to play the audio before user interaction. There is no way to hack this. This is to prevent page from annoying users. So to achieve this, we have to wait until user interaction. User clicks can be treated as user interaction. So add a event lister to window and implement your code there.
Not that, audio will play only after user clicks anywhere in the window.