Mediaelement.js Flash fallback pain.

Recently I’ve been working a lot with mediaelement.js, much more than I’d hoped to have to have done with a module that promises so much.

The biggest issue I faced was changing the video src in the Flash fallback player as when you change the source the new video isn’t loaded until it is played. I’ve cursed this player for a whole day, but I can’t rule out that the Flash implementation is to blame.

Possible workarounds were to have the videos autoplay or to replace the fallback whenever the src was changed. The final workaround was to change the source, call play, and then pause the video after a timeout so the user doesn’t see it playing. And that works, but it relies upon a timeout that is unconnected to anything happening in the page.

Fortunately there are events raised by the HTML5 player and the fallback that we can use to bind onto to improve the flow of our somewhat shitty workaround.

(You might wonder why these events couldn’t solve our setSrc problem anyway, but as the video isn’t loaded at all until play is called, not even when .load() is called, then they’re a red herring)

 
//watch for the canplay event, bound above the video element. At this point the video is in a play state 
videoContainer.on('canplay', function (event, mediaElement) { 
//paused the video 
mediaElement.pause(); 
}); 

In my full code it’s a little more complex, as sometimes we actually want it to play, but that is the basic hook.

Update: Firefox is firing the canplay event in some situations as the events true purpose is to track when there is enough of a video for it to play. Our workaround is only required for the fallback, so we can add the canplay event to that only.

Filed under: JavaScript