Making a Custom YouTube Video Player With YouTube's APIs #2

Gauloran

Kıdemli Moderatör
7 Tem 2013
8,119
599
local
In the second part of the code, we use the SWFObject plugin to generate the embed code of the youtube chromeless player. Notice that the id of the video is passed as a flashvar so the player can load it directly. The safeID variable (a JavaScript safe version of the videoid) becomes the value of the id parameter of the to-be generated object element. This way we can later fetch the DOM element by running ********.getElementById('video_'+settings.safeID) and get access to the methods which control the youtube player (play, pause etc).

youTubeEmbed-jquery-1.0.js - Part 3

Kod:
var initialized = false;

// Creating a global event listening function for the video
// (required by YouTube's player API):

window['eventListener_'+settings.safeID] = function(status){

    var interval;

    if(status==-1)  // video is loaded
    {
        if(!initialized)
        {
            // Listen for a click on the control button:

            elements.control.click(function(){
                if(!elements.container.hasClass('playing')){

                    // If the video is not currently playing, start it:

                    elements.control.removeClass('play replay').addClass('pause');
                    elements.container.addClass('playing');
                    elements.player.playVideo();

                    if(settings.progressBar){
                        interval = window.setInterval(function(){
                            elements.elapsed.width(
                    ((elements.player.getCurrentTime()/data.duration)*100)+'%'
                            );
                        },1000);
                    }

                } else {

                    // If the video is currently playing, pause it:

                    elements.control.removeClass('pause').addClass('play');
                    elements.container.removeClass('playing');
                    elements.player.pauseVideo();

                    if(settings.progressBar){
                        window.clearInterval(interval);
                    }
                }
            });

            initialized = true;
        }
        else{
            // This will happen if the user has clicked on the
            // YouTube logo and has been redirected to youtube.com

            if(elements.container.hasClass('playing'))
            {
                elements.control.click();
            }
        }
    }
In order to be able to control the video player, we need to be notified when certain events (like playback stopped, video ready etc) occur. Normally, this would mean that we need to pass a callback function, which is executed by the player every time such an event happens.

Unfortunately, flash can only execute functions if they are defined in the global scope and cannot see the functions which are defined inside the plugin. However, by creating functions with unique names (with the safeID) and explicitly adding them to the window object we can make this happen. If it weren't for this little trick, it would be impossible for the plugin to work.

youTubeEmbed-jquery-1.0.js - Part 4
Kod:
    if(status==0){ // video has ended
                    elements.control.removeClass('pause').addClass('replay');
                    elements.container.removeClass('playing');
                }
            }

            // This global function is called when the player is loaded.
            // It is shared by all the videos on the page:

            if(!window.onYouTubePlayerReady)
            {
                window.onYouTubePlayerReady = function(playerID){
                    ********.getElementById('video_'+playerID).addEventListener('onStateChange','eventListener_'+playerID);
                }
            }
        },'jsonp');

        return elements.originalDIV;
    }

})(jQuery);
The event listening function we created in the previous section of the code, is attached to the player with the addEventListener method. It is called every time when a "stateChange" occurs (playback start, playback pause, end of playback etc). A numeric code is passed to the event listening function as a parameter, corresponding to the event.

Now lets take a look at how our plugin is used.

script.js
Kod:
$(********).ready(function(){

    $('#player').youTubeEmbed('http://www.youtube.com/watch?v=u1zgFlCw8Aw');

    /*
        //You can alternatively pass an object:

        $('#player').youTubeEmbed({
            video           : 'http://www.youtube.com/watch?v=u1zgFlCw8Aw',
            width           : 600,      // Height is calculated automatically
            progressBar : false     // Hide the progress bar
        });

    */

});
You just need to call the youTubeEmbed() method and pass it either a string or a configuration object. If a string is passed, it is assumed to be the URL of a YouTube video. If you are passing an object make sure that you are passing the video property with a correct video URL.

i21.jpg


Step 3 - CSS
Finally we are left with applying a few CSS styles to the player. They will change the design of the player controls and define the way they are positioned in the player window.

youTubeEmbed-jquery-1.0.css
Kod:
.flashContainer{

    /*  Setting the container to relative positioning
        so we can center the control div */

    position:relative;
    overflow:hidden;
}

.progressBar{
    display:none;
    position:absolute;
    width:auto;
    height:8px;
    left:20px;
    right:105px;
    bottom:20px;
    background-color:#141414;
    overflow:hidden;
    cursor:pointer;

    /* A light CSS3 bottom highlight */

    -moz-box-shadow:0 1px 0 rgba(255, 255, 255, 0.3);
    -webkit-box-shadow:0 1px 0 rgba(255, 255, 255, 0.3);
    box-shadow:0 1px 0 rgba(255, 255, 255, 0.3);
}

.progressBar .elapsed{
    position:absolute;
    width:0;
    height:100%;
    background-color:#1fa2f6;
    border-right:1px solid #49AFF0;
}

.controlDiv{
    /* Centering the control div */
    position:absolute;
    width:120px;
    height:120px;
    cursor:pointer;
    top:50%;
    left:50%;
    margin:-60px 0 0 -60px;
}

.controlDiv.play{
    background:url('img/play.png') no-repeat center center;
}

.controlDiv.replay{
    background:url('img/replay.png') no-repeat center center;
}

.controlDiv.pause{
    background:url('img/pause.png') no-repeat -99999px;
}

.flashContainer:hover .controlDiv.pause{
    background-position:center center;
}

/* Only show the progress bar when the video is playing */

.flashContainer.playing:hover .progressBar{
    display:block;
}
To customize the look of the player you just need to change the color values above. Also you can edit the png files with the play/pause buttons. Clearly this is much easier than modifying the looks of the default youtube player. It also strips all of the unnecessary chrome and leaves you with what matters most - your video.

With this our Custom YouTube Player plugin is complete!

Did you like this tutorial? Share your thoughts in the comment section below.​
 
Üst

Turkhackteam.org internet sitesi 5651 sayılı kanun’un 2. maddesinin 1. fıkrasının m) bendi ile aynı kanunun 5. maddesi kapsamında "Yer Sağlayıcı" konumundadır. İçerikler ön onay olmaksızın tamamen kullanıcılar tarafından oluşturulmaktadır. Turkhackteam.org; Yer sağlayıcı olarak, kullanıcılar tarafından oluşturulan içeriği ya da hukuka aykırı paylaşımı kontrol etmekle ya da araştırmakla yükümlü değildir. Türkhackteam saldırı timleri Türk sitelerine hiçbir zararlı faaliyette bulunmaz. Türkhackteam üyelerinin yaptığı bireysel hack faaliyetlerinden Türkhackteam sorumlu değildir. Sitelerinize Türkhackteam ismi kullanılarak hack faaliyetinde bulunulursa, site-sunucu erişim loglarından bu faaliyeti gerçekleştiren ip adresini tespit edip diğer kanıtlarla birlikte savcılığa suç duyurusunda bulununuz.