While building the page, I found out that on iOS mobile Safari, you cannot start playing an HTML5 audio tag without user action (click or tap). So for instance, you cannot use a server-side JS view response for triggering an HTML5 audio or video play. The reason why automatic/server-side control is disabled, is because you don't want random audio/video-tags around the web steal your mobile data package and cost you a lot of money.
So how do you start playing a HTML5 audio-tag from JS with a custom play button? Here's a sample in CoffeeScript:
$(document).on "click", ".play-button", (e) -> audioplayer_id = $(e).data("audio-player-id") audioplayer = $("#" + audioplayer_id) audioplayer_element = audioplayer audioplayer_element.load() audioplayer_element.play()
The reason I'm calling
load() on every play-click is that I'm using live streaming source URLs for the audio tag. When calling
load() I make sure that the stream gets re-buffered from the current moment.
Sample: Stop other elements when playing one
My page shows multiple audio tags, so when you start listening to one, I want to pause the other audio tags. Here's how I do that:
$(document).on "click", ".play-button", (e) -> audioplayer_id_to_play = "#" + $(e).data("audio-player-id") $("audio.audioplayer").each -> audioplayer_element = $(this) audioplayer_id = $(this).attr("id") if audioplayer_id == audioplayer_id_to_play audioplayer_element.load() audioplayer_element.play() else audioplayer_element.pause()