Tuesday, May 31, 2016

Auto play HTML5 video on iPhone and iPAD

One of the holy grails of the online advertising industry, is the ability to automatically play video ads on mobile devices. 
Both Apple and Google prevent auto playback of video files on mobile devices running iOS and Android.
There are few solutions for this issue, most of them rely on rendering an image sequences to a Canvas element.

I've made some simple changes to my inline playback demo to enable auto playback of HTML5 videos on iOS. Sadly, this solution doesn't work on Android.
The solution is very simple. The video starts muted, as required by the online advertisement industry. Clicking the video enables audio as well.
On the iPhone, auto playback starts muted and inline. Clicking the video jumps to fullscreen playback with audio.
  • Demo: Open this link on your iPhone or iPAD to see the demo.
  • Code: View the full source code on Github
Code sample:

    var vid = document.getElementById("vid"); // get reference to the video object
    var intervalID = null;
    var time = 0;
    var speed = 15; // frames per seconds (fps). Change this value to balance quality against performances

    // wait for the onloadedmetadata event to get the video duration
    vid.onloadedmetadata = function() {
        var duration = vid.duration;
        intervalID = setInterval(function(){
            time++;
            if (time / speed <=  duration){
                vid.currentTime = time / speed;
            }else{
                clearInterval(intervalID);
                intervalID = null;
            }
        },1000 / speed);
    };

    // clicking the video stops inline playback and triggers native playback including audio. No need to seek.
    vid.addEventListener('click', function(){
        clearInterval(intervalID);
        intervalID = null;
        this.play();
    });



Explanation:

  1. Define the playback speed in FPS (frames per seconds)
  2. Wait for the onloadedmetadata event after which video currentTime property can be set
  3. Open a timer interval according to the defined speed and advance the video currentTime property on each interval
  4. Stop the interval when the video reaches its duration or clicked upon
  5. Upon video click execute the play() command on the video element
That's it!

About Me

My photo
I've been developing Internet and rich-media application for 15 years. In my work I emphasis usability and best user experience as well as sleek design. My main expertise are JavaScript, Flex and Flash.

Followers