0

I'm having an issue playing audio on some mobile and ipad devices.

HTML:

<audio id="audio"></audio>
<button id="play-audio">Play Audio</button>
<button id="retry" style="display:none">Retry To Play Audio</button>

JS:

$('#play-audio').click(function(){
    $.ajax({
        url: "../audio/audio.json",
        type: 'GET',
        dataType: "json",
        success: function(response) {
            var audio = document.getElementById('audio'),
                retry = document.getElementById('retry');

            audio.src = response.sound;
            audio.play();

            audio.onplaying = function(e){
                console.log('audio is playing');
            };

            audio.onerror = function(e){
                console.log('error');

                retry.style.display = "block";
    
                retry.onclick = function(){
                    audio.play();
                }
            };
        }
    });
});

When the user clicks "#play-audio" an Ajax call is made that fetches the audio file path, appends it to the audio tag src, and plays that audio. If an error occurs on playing that audio the #retry button is shown to play the audio on clicking. The issue on some devices in the console is I get Uncaught (in promise) NotAllowedError and the onerror event is not fired.

I tried to add audio.load(); before audio.play(); didn't work. Also, I tried to check onabort event:

audio.onabort = function(e){
    console.log('audio aborted');
}; 

None of these events is fired I get nothing printed in the console but that error NotAllowedError.

mm1234
  • 23
  • 5

1 Answers1

0

It might sound silly, but you don’t click on mobile, you touch instead!

You might find the touch event useful: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events

Keep in mind, jquery doesn’t carry much functionality for this. So, add your event listener like this:

document.getElementById(“retry”).addEventListener(“touchend”, function () { [Your function here] })
LarryTLlama
  • 154
  • 7
  • Sorry, maybe I couldn't explain the problem. The issue is not with clicking the button but the audio not playing and onerror event not fired when this happens – mm1234 Jun 11 '23 at 21:41
  • Ah okay, apologies for my incorrect response. Have you tried adding an event listener to the "canplaythrough" event? This detects when permissions allow you to play again:. See the MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement/Audio#determining_when_playback_can_begin – LarryTLlama Jun 12 '23 at 09:52
  • I tried to fire `audio.play()` with that even but it's not working and showing the same error – mm1234 Jun 12 '23 at 18:33
  • Hmm, you definitely don't have permissions from safari. Have you tried using it without using jquery? You can do that in standard js by using `document.getElementById("#play-audio").addEventListener("click", function() { [...] })` and placing your ajax call in the function. – LarryTLlama Jun 13 '23 at 09:26