skip to Main Content

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


  1. Browsers are often blocking sounds that are not triggered by user interaction, you can start playing the audio on the mouse move for example:

    let isAjaxLoaded = false;
    
    $(document).mousemove(function(){
      if (isAjaxLoaded) {
        playAudio();
      }
    });
    
    $.ajax({
      url: '{{url('/')}}',
      type: 'POST',
      data: {
        _token: _token
      },
      dataType: 'json',
      success: function(response) {
        if (response.code == 1) {
          isAjaxLoaded = true;
        }
      }
    });
    
    function playAudio() {
      var x = document.getElementById("myAudio");
      x.play();
    }
    
    Login or Signup to reply.
  2. 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.

    $.ajax({
      url: '{{url('/')}}',
      type: 'POST',
      data: {
        _token: _token
      },
      dataType: 'json',
      success: function(response) {
        if (response.code == 1) {
          window.addEventListener('click', ()=> {
              playAudio();
          })
        }
      }
    });
    
    function playAudio() {
      var x = document.getElementById("myAudio");
      x.play();
    }
    

    Not that, audio will play only after user clicks anywhere in the window.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search