14.08.2013

How To Optimize a Youtube Video Dimension on your mobile device

Bind the eventListener

First thing what we need is an EventListener on "orientationchange". For this i use Ender with bean for that.

//in which orientation
var MOrientation;
$.domReady(function(){

    // Listen for orientation changes
    window.addEventListener("orientationchange", function() {
        bean.fire(document,'device-orientation',[is_landscape()?'LandScape':'Portrait']);
    }, false);


    function is_landscape() {
        return (window.orientation === 90 || window.orientation === -90);
    }

    MOrientation = is_landscape()?'LandScape':'Portrait';
});

Next Step

We calculate the dimension for the initial video implementation.

var self = this,
    width = MOrientation === 'Portrait'?screen.width:screen.height,
    height = (width/16)*9;//16:9 'widescreen'

on orientationchange

We need the listener on the change event.

bean.on(document,'device-orientation',function(orientation){

                log(orientation);
                if(orientation === 'LandScape')
                {
                    $('#player').css('height',(screen.height/16*9));
                }else{
                    $('#player').css('height',(screen.width/16*9));
                }
            });

Fullscript

/**
 * @author Pascal Brewing
 * @email pb@becklyn.com
 */
//in which oreientation
var MOrientation;
$.domReady(function(){

    // Listen for orientation changes
    window.addEventListener("orientationchange", function() {
        bean.fire(document,'device-orientation',[is_landscape()?'LandScape':'Portrait']);
    }, false);


    function is_landscape() {
        return (window.orientation === 90 || window.orientation === -90);
    }

    MOrientation = is_landscape()?'LandScape':'Portrait';
});
/**
 * its global because the Youtube Api Call this functions
 */
var player;
var bean = require('bean');

function onYouTubeIframeAPIReady() {
    var bean = require('bean');
    bean.fire(document,'youtube-api-ready');
}
/**
 * Ready Steady GO ......
 * @param event
 */
function onPlayerReady(event) {
    var bean = require('bean');
    bean.fire(document,'videoplayer-on-ready',[event.target]);
}

/**
 * Oh its A Youtube!!!
 * https://developers.google.com/youtube/iframe_api_reference
 *
 * -1 (unstarted)
 * 0 (ended)
 * 1 (playing)
 * 2 (paused)
 * 3 (buffering)
 * 5 (video cued)
 *
 * YT.PlayerState.ENDED
 * YT.PlayerState.PLAYING
 * YT.PlayerState.PAUSED
 * YT.PlayerState.BUFFERING
 * YT.PlayerState.CUED
 * @param event
 */
/*global MOrientation:true */
function onPlayerStateChange(event) {
    var done = false;
//    console.log(['event.data',event.data]);
//    console.log(['YT.PlayerState',YT.PlayerState]);

    if (event.data == YT.PlayerState.PLAYING && !done) {
        bean.fire(document,'videoplayer-played');
        done = true;
    }else if(event.data == YT.PlayerState.PAUSED && !done){
        bean.fire(document,'videoplayer-paused');
        done = true;
    }else if(event.data == YT.PlayerState.BUFFERING && !done){
        bean.fire(document,'videoplayer-buffering');
        done = true;
    }else if(event.data == YT.PlayerState.ENDED && !done){
        bean.fire(document,'videoplayer-ended');
        done = true;
    }else if(event.data == YT.PlayerState.UNSTARTED && !done){
        bean.fire(document,'videoplayer-unstarted');
        done = true;
    }

}


/*global ender:true */
(function ($) {
    "use strict";
    /**
     * ender package
     * @type {*}
     */
    var qwery = require('qwery-mobile');
    /**
     * ender package
     * @type {*}
     */
    var bonzo = require('bonzo');
    /**
     * ender package
     * @type {*}
     */
    var bean = require('bean');
    /**
     * the video ID from youtube
     * @type {string}
     */
    var videoId = '';
    /**
     *
     * @type {{$_player: string, $_xml: string, $_debug: boolean, init: Function, _registerEventListener: Function, _apiLoaded: Function, _loadVideoPlayer: Function, requireYouTubeApi: Function, _playerPlayed: Function, _playerPaused: Function, _playerBuffering: Function, _playerEnded: Function, _playerUnstarted: Function}}
     */
    var VideoPlayer = {
        $_player:'',
        $_xml:'',
        $_debug:false,
        /**
         * init the Module
         * @param xml
         */
        init: function () {
            var self = this;
            videoId = 'dkHJKakHMpo';
            self._registerEventListener();
            self.requireYouTubeApi();

        },
        /**
         * listen to the trigger
         * @private
         */
        _registerEventListener:function(){
            var self = this;
            //load youtube api
            bean.on(document,'loadVideo', self._loadVideoPlayer);
            bean.on(document,'youtube-api-ready',self._apiLoaded);
            bean.on(document,'videoplayer-on-ready',function(){
                log('ready');
            });

            //controls videoplayer
            bean.on(document,'videoplayer-played',self._playerPlayed);
            bean.on(document,'videoplayer-paused',self._playerPaused);
            bean.on(document,'videoplayer-buffering',self._playerBuffering);
            bean.on(document,'videoplayer-unstarted',self._playerUnstarted);
            bean.on(document,'videoplayer-ended',self._playerEnded);
        },
        /**
         * Api is loaded from extern
         * @param event
         * @private
         */
        _apiLoaded:function(event){
            var self = this;
            log(['xml',event]);
            bean.fire(document,'loadVideo',[videoId]);
        },
        /**
         *
         * @param videoId
         * @private
         */
        _loadVideoPlayer:function(videoId){
            var self = this,
                width = MOrientation === 'Portrait'?screen.width:screen.height,
                height = (width/16)*9;

            player = new YT.Player('player', {
                width: width,
                height:height,
                videoId:videoId,
                playerVars: {
                    rel: 0,
                    autohide:1,
                    modestbranding:1,
                    showinfo:0

                },
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                }
            });

            bean.on(document,'device-orientation',function(orientation){

                log(orientation);
                if(orientation === 'LandScape')
                {
                    $('#player').css('height',(screen.height/16*9));
                }else{
                    $('#player').css('height',(screen.width/16*9));
                }
            });
        },
        /**
         * if finished Youtube call the
         * onYouTubeIframeAPIReady func
         */
        requireYouTubeApi:function(){
            var self = this;
            var tag = document.createElement('script');
            tag.src = "https://www.youtube.com/iframe_api";
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
        },
        /**
         * this event ist triggered when the player is on played
         * @private
         */
        _playerPlayed:function(){
            log('player played');
        },
        /**
         * * this event ist triggered when the player is on pause
         * @private
         */
        _playerPaused:function(){
            log('player paused');
        },
        /**
         * this event ist triggered when the player is on buffering
         * @private
         */
        _playerBuffering:function(){
            log('player buffering');
        },
        /**
         * this event ist triggered when the player is on end
         * @private
         */
        _playerEnded:function(){
            log('player ended');
        },
        /**
         * * this event ist triggered when the player is on unstarted
         * @private
         */
        _playerUnstarted:function(){
            log('player ready but not started');
        }

    };

    //debug logger
    function log(ob) {
        if (VideoPlayer.$_debug && console != undefined)
            console.log(['Video.js :', ob]);
    }
    /**
     * Initializes the component
     */
    $.domReady(function(){
        
        VideoPlayer.init();
    });
}(ender,MOrientation));
 

Leave a Comment