I'm currently building a Web Audio Player, which is already working on all major desktop browsers. However, Safari on iOS has a very strange behavior when it comes to its autoplay restrictions.
When a user loads up the audio player, he has two options to start playing a track. Either he clicks the obvious play button at the bottom of the play controls (I element) or he clicks a track in the playlist (div element).
Both of these options execute the same code, the only difference is the event handler.
The play button option works, safari is not complaining about it. The playlist item click option does not work. Safari gives me this error:
Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
Does Safari restrict by what kind of element click event handler is used?
Here's the code for both options:
var ePlay = jQuery('.player .player-controls .play-toggle');
// <--- <i> Element
var ePlaylistSingleTrack = jQuery('.player .playlist .single-track');
// <--- DIV Element
jQuery(ePlay).click(function(){
if (audioElement.paused){
playAndVisualize();
} else {
audioElement.pause();
jQuery(this).removeClass('fa-pause-circle');
jQuery(this).addClass('fa-play-circle');
}
});
jQuery(ePlaylistSingleTrack).click(function(){
if (audioElement.paused){
playAndVisualize();
} else {
audioElement.pause();
jQuery(this).removeClass('fa-pause-circle');
jQuery(this).addClass('fa-play-circle');
}
});
EDIT 1: I've tried using standard event listeners instead of using jquery. No changes. I also tried using an I - Element instead of a div, but that also didnt help.
So Mobile Safari doesn't like fake click events because its a touch device. you have to use touch events. Typically I do this on all projects because it solves other issues i have come across with mobile safari.
var myEvent = ('ontouchstart' in document.documentElement) ? 'touchend' : 'click';
document.querySelector('.your-selector-here').addEventListener(myEvent, function () {
// Your Listener here
});