Friday, 20 November 2015

Integrate AEM with YouTube

You can use youtube API to add video in your webpages. Below is the sample code snippet for embedding youtube videos into your webpages.

Note:  In order to make sure your javascript works, add "enablejsapi=1" parameter to the src atttribute. Please check below HTML code.

HTML Code

<h1>In page youtube video player API</h1>
<br/>
<h2><span id="YTvideoLoadTime"></span> </h2>

<h3>Check console logs for player events</h3>
<iframe id='player' width="560" height="315" 
src="https://www.youtube.com/embed/axCKOu3YjmM?list=PLkBe8kbE_7-xmNihqYr19TlYGH7jUhQkY&enablejsapi=1" frameborder="5" allowfullscreen></iframe>



Javascript:

//YOUTUBE API
var player;
var timerStart, timetaken;

jQuery(document).ready(function ($) {
    console.log("ready!");
    loadPlayer();
});

function getArtistId() {
    return 'axCKOu3YjmM';
}

function loadPlayer() {
   console.log("Youtube IFRAME api");
    timerStart = Date.now();
    if (typeof (YT) == 'undefined' || typeof (YT.Player) == 'undefined') {
        var tag = document.createElement('script');        
        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        window.onYouTubePlayerAPIReady = function () {
           // console.log("YT undefined calling onYouTubePlayer ");
            onYouTubePlayer();
        };

    } else {
       // console.log("calling onYouTubePlayer ");
        onYouTubePlayer();

    }
}


function onYouTubePlayer() {
    player = new YT.Player('player', {
        // height: '490',
        //width: '880',
       // videoId: getArtistId(),
       // playlist: 'PLkBe8kbE_7-xmNihqYr19TlYGH7jUhQkY',
        playerVars: {
            controls: 1,
            showinfo: 0,
            rel: 0,
            showsearch: 0,
            iv_load_policy: 3
        },
        events: {
            'onStateChange': onPlayerStateChange,
                'onError': catchError,
                'onReady': onPlayerReady
        }
    });
}

var done = false;

function onPlayerStateChange(event) {
    console.log("onPlayerStateChange: " + event.data);
    if (event.data == YT.PlayerState.PLAYING ) {
        console.log("playing");
        done = true;
    } else if (event.data == YT.PlayerState.ENDED) {
        console.log("ended");
        location.reload();
    }
    else if (event.data == YT.PlayerState.PAUSED) {
        console.log("paused");
    }
}

function onPlayerReady(event) {
    //console.log("onPlayerReady");
    timetaken = Date.now() - timerStart;
    $('#YTvideoLoadTime').html("Youtube Video player has loaded in : " + timetaken / 1000 + " seconds");

}

function catchError(event) {
    if (event.data == 100) console.log("ERROR");
}

function stopVideo() {
    console.log("stopVideo");
    player.stopVideo();
}



No comments :

Post a Comment