javascript - How can I find when HTML5 audio actually starts playing (onplay event does not seem to work anywhere) -
i need catch exact moment when html5 audio starts producing sound.
it turns out not simple seems.
you might expect audio starts playing when onplay
or onplaying
event fired? no way. @ least in webkit family, seems no browser event fires @ point of time. in chrome, safari , firefox onplay
, onplaying
events faking behaviour firing oncanplay
!
i've prepared simple test prove fact. demonstrates audio starts playing after reasonable time (over 100ms - 400ms) when events had been fired.
you can notice ears , ears if @ console log. in log output currenttime
every 15ms. seems reflect actual audio state correctly, , starts changing 10-40 polls after event has been fired. audio still freezed after play
fired.
test code looks this:
var audioel = new audio('http://www.w3schools.com/tags/horse.ogg'); audioel.oncanplay = function () { console.log('oncanplay'); audioel.currenttime = 1; console.log('ready state is: ' + audioel.readystate); audioel.play(); } audioel.oncanplay = function () { console.log('oncanplay again'); } audioel.onplay = function() { console.log('onplay -----------------'); } audioel.onplaying = function() { console.log('onplaying ----------------'); } setinterval(function () { console.log(audioel.currenttime); }, 15);
jsfiddle
i critically need know exact moment when audio starts playing precise synchronisation visual animations.
of course, can find moment using quick polling. bad performance in real-time app, on mobile.
i'm asking if knows better solution this. html audio implementation looks still poor in 2014 :(
as @justin says, can listen playing
event (more or less) precise moment media starts playing. yeah i've been seeing spotty support media events , readystate
in general, even in latest chrome.
whether events work or not, advise against using setinterval
animation (or else, matter). instead, use requestanimationframe
, fire more , should synchronize browser , video card's repaint. , can poll currenttime
value on every frame calculate should in animation. performance shouldn't problem; case exactly requestanimationframe
designed for.
function update() { var currenttime = audioel.currenttime; // update animation here requestanimationframe(update); } update();
while you're @ it, don't set currenttime
5 until after readystate > 0
or loadedmetadata
event fires. if try set currenttime
before browser has loaded enough of video file know duration, throw error. can call play()
whenever want; doesn't have wait canplay
.
Comments
Post a Comment