While I’m not exactly sure what causes the delay on an iOs device I’d recommend a workaround which should work no matter what browser is being used.
Instead of listening for a play or playing events, listen for the timeUpdate event. Inside the callback function simply check if the .currentTime property of your audio element is bigger than zero.
document.getElementById('audio').addEventListener("timeupdate", update, false);
document.getElementById('audio').addEventListener("play", play, false);
var started = false;
var playPushed = false;
var startTime;
function update() {
if (playPushed && !started && document.getElementById('audio').currentTime > startTime) {
started = true;
var h = document.createElement("H1");
var t = document.createTextNode('playing');
h.appendChild(t);
document.body.appendChild(h);
}
}
function play() {
playPushed = true;
startTime = document.getElementById('audio').currentTime;
}
<audio id="audio" controls preload="auto">
<source src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_5MG.mp3" type="audio/mpeg" />
</audio>
I am trying to detect when audio starts playing on ios. The problem is that play, playing events fire immediatelly when I press play but audio start playing couple seconds later. I am using ~ 5mb audio file.
Why is there such delay between these evets and audio start, and how can I detect when sound actually starts?
document.getElementById('audio').addEventListener("play", play, false);
document.getElementById('audio').addEventListener("playing", playing, false);
function play() {
var h = document.createElement("H1");
var t = document.createTextNode('play');
h.appendChild(t);
document.body.appendChild(h);
}
function playing() {
var h = document.createElement("H1");
var t = document.createTextNode('playing');
h.appendChild(t);
document.body.appendChild(h);
}
<audio id="audio" controls preload="auto">
<source src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_5MG.mp3" type="audio/mpeg" />
</audio>
Here is jsfiddle, you can check on ipad.
https://jsfiddle.net/pmw8fa5e/1/
Ugly fix, but could work for as media started event, but if you listen for play event constantly (for example to change pause / play icon on your player) then you need to get this event every time.