📜 ⬆️ ⬇️

Youtube Player - creating your own JavaScript player

Introduction


Surely many front-end developers and, in general, many users at least once were interested in the work and functioning of the Youtube Player. In this article I will tell you how it works, and how to make your player to play Youtube video with its interface. I will also give examples for understanding how this works.

For a regular user, the link to the video from the outside might look like this: www.youtube.com/watch?v= {video_id} . Or, for example, like this: youtu.be/{video_id} - where video_id is the video identifier in the Youtube database (it is unique for each video and the most important information on which the video is drawn, links are formed, etc.). For example, let’s take it so as not to offend anyone (and don’t give a fuck on God blessing) video_id = CyVuYAHiZb8 - video clip from Ray Charles - Hit the Road.

As many know, to insert the actual video on your website there is a simple opportunity to “copy the HTML code” when you right-click on the video in Youtube and get in the iframe buffer:

<iframe width="640" height="360" src="https://www.youtube.com/embed/CyVuYAHiZb8" frameborder="0" allowfullscreen></iframe> 

Such an iframe can be managed on its website. Next, I’ll tell you how to do this using the example of creating your own controls and event handlers in Javascript + Jquery.
')

Player Page - Layout


First we create a simple html-page, in which there will be several div-blocks, to which we will link our player.

HTML code of the page
 <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.8.3.js"></script> <!-- jQuery --> <script src="https://www.youtube.com/iframe_api"></script> <!--    iframe_api--> <link rel='stylesheet' id='fortunato-style-css' href='http://your.styles.css' type='text/css' media='' /> <!--  (   css )--> </head> <body> <div class="panel"> <button id="back" onclick="player.previousVideo();">Back</button> <button id="play" onclick="player.playVideo();">Play</button> <button id="pause" onclick="player.pauseVideo();">Pause</button> <button id="next" onclick="player.nextVideo();">Next</button> <div id="time">00:00</div> <div id="line" onclick="progress (event);"> <div class="viewed"></div> <div id="fader" onclick="alert('fader');"></div> </div> <button id="volume" onclick="editVolume ();"></button> <div id="quality">Auto</div> <button id="full" onclick="playFullscreen ();">FullScreen</button> </div> <div> <button id="playlist" onclick="loadPlaylistVideoIds();">Load New Playlist</button> <button id="qual" onclick="editQuality ();">   480</button> </div> </body> </html> 



Button and player styles
 body { margin: 0; } .panel { width: 850px; height: 40px; background: grey; margin-top: -5px; border: 1px solid #aaa; } #play, #back, #next, #pause{ float: left; width: 50px; height: 40px; } #time{ float: left; width: 50px; height: 40px; color: #fff; padding-top: 10px; margin-left: 10px; } #line{ margin-top: 15px; height: 4px; width: 350px; background: #fff; float: left; margin-right: 15px; } #volume { float: left; width: 80px; height: 40px; } #quality{ float: left; width: 50px; height: 40px; color: #fff; padding-top: 10px; margin-left: 10px; } #full { float: left; width: 75px; height: 40px; } #fader { background: black; border-radius: 5px; width: 10px; height: 10px; position: relative; z-index: 4; bottom: 3px; } #playlist { margin-top: 20px; } .viewed { position: absolute; background: red; height: 4px; } 


And most importantly - javascript.

To create and initialize the player via iframe api, you need a div with an identifier to which the iframe will be attached to the video. In our case it is
 <div id="player"></div> 


Player Management - JavaScript


No matter where you put it, but the main thing is below the link libraries (for simplicity, you can right in the html-document).

All Javascript Code Functions
 //  function onYouTubeIframeAPIReady() { player = new YT.Player('player', { height: '500', playerVars: { 'autoplay': 0, 'controls': 0, 'showinfo': 0, 'rel': 0}, width: '850', videoId: 'CyVuYAHiZb8', events: { 'onReady': onPlayerReady } }); } //   function onPlayerReady(event) { var player = event.target; iframe = document.getElementById('player'); setupListener(); updateTimerDisplay(); updateProgressBar(); time_update_interval = setInterval(function () { updateTimerDisplay(); updateProgressBar(); }, 1000); } /* */ function setupListener (){ document.getElementById('full').addEventListener('click', playFullscreen); } /* */ function playFullscreen (){ player.playVideo();//won't work on mobile var requestFullScreen = iframe.requestFullScreen || iframe.mozRequestFullScreen || iframe.webkitRequestFullScreen; if (requestFullScreen) { requestFullScreen.bind(iframe)(); } } /* */ function loadPlaylistVideoIds(); { player.loadPlaylist({ 'playlist': ['9HPiBJBCOq8', 'Mp4D0oHEnjc', '8y1D8KGtHfQ', 'jEEF_50sBrI'], 'listType': 'playlist', 'index': 0, 'startSeconds': 0, 'suggestedQuality': 'small' }); } /**/ function editVolume () { if (player.getVolume() == 0) { player.setVolume('100'); } else { player.setVolume('0'); } } /**/ function editQuality () { player.setPlaybackQuality('medium'); document.getElementById('quality').innerHTML = '480'; } //     -  function updateTimerDisplay(){ document.getElementById('time').innerHTML = formatTime(player.getCurrentTime()); } /* */ function formatTime(time){ time = Math.round(time); var minutes = Math.floor(time / 60), seconds = time - minutes * 60; seconds = seconds < 10 ? '0' + seconds : seconds; return minutes + ":" + seconds; } //   function updateProgressBar(){ var line_width = jQuery('#line').width(); var persent = (player.getCurrentTime() / player.getDuration()); jQuery('.viewed').css('width', persent * line_width); per = persent * 100; jQuery('#fader').css('left', per+'%'); } /* */ function progress (event) { var line_width = jQuery('#line').width(); //   var pos = jQuery('#line').offset(); var elem_left = pos.left; //     var Xinner = event.pageX - elem_left; var newTime = player.getDuration() * (Xinner / line_width); // Skip video to new time. player.seekTo(newTime); } 



And now how it works. First we create the player - this requires a mandatory function:

  //  function onYouTubeIframeAPIReady() { player = new YT.Player('player', { height: '500', playerVars: { 'autoplay': 0, 'controls': 0, 'showinfo': 0, 'rel': 0}, width: '850', videoId: 'CyVuYAHiZb8', events: { 'onReady': onPlayerReady } }); } 

It seems to be called by itself immediately, and inside it a YT.Player object is created with parameters. First 'player' - id
 <div id="player"></div> 
to which at initialization iframe clings. Further, height and width - iframe, videoId dimensions: 'CyVuYAHiZb8' - the video identifier is our Ray Charles. playerVars: {'autoplay': 0, 'controls': 0, 'showinfo': 0, 'rel': 0} are the player settings, they speak for themselves - cost zeroes to turn off the controls we make our own.

And events: {'onReady': onPlayerReady} is a hook that hooks a method to handle a read event. Next is this function, it contains methods for handling events, etc.

Now for the player object. It is created and it can be controlled by calling methods, like in the control panel in html buttons.

HTML code of the player panel
 <div class="panel"> <button id="back" onclick="player.previousVideo();">Back</button> <button id="play" onclick="player.playVideo();">Play</button> <button id="pause" onclick="player.pauseVideo();">Pause</button> <button id="next" onclick="player.nextVideo();">Next</button> <div id="time">00:00</div> <div id="line" onclick="progress (event);"> <div class="viewed"></div> <div id="fader" ></div> </div> <button id="volume" onclick="editVolume ();"></button> <div id="quality">Auto</div> <button id="full" onclick="playFullscreen ();">FullScreen</button> </div> <div> <button id="playlist" onclick="loadPlaylistVideoIds();">Load New Playlist</button> <button id="qual" onclick="editQuality ();">   480</button> </div> 



Play and pause buttons
 <button id="play" onclick="player.playVideo();">Play</button> 
- play
 <button id="pause" onclick="player.pauseVideo();">Pause</button> 
- pause
Here everything is just play-pause.

Back and next buttons
 <button id="back" onclick="player.previousVideo();">Back</button> <button id="next" onclick="player.nextVideo();">Next</button> 

These buttons are needed to switch the video in the playlist.

To create a playlist there is a button
 <button id="playlist" onclick="loadPlaylistVideoIds();">Load New Playlist</button> 
- which calls the function on click.

This function calls the player.loadPlaylist ({....}) method.
 function loadPlaylistVideoIds(); { player.loadPlaylist({ 'playlist': ['9HPiBJBCOq8', 'Mp4D0oHEnjc', '8y1D8KGtHfQ', 'jEEF_50sBrI'], 'listType': 'playlist', 'index': 0, 'startSeconds': 0, 'suggestedQuality': 'small' }); } 

with playlist parameters: ['9HPiBJBCOq8', 'Mp4D0oHEnjc', '8y1D8KGtHfQ', 'jEEF_50sBrI'] - list of videos in the playlist. 'listType': 'playlist' - type, 'index': 0 - index of the video from which to start, the other parameters are obvious. So playlists are loaded. You can also initialize the playlist right at the beginning, then you need to set playerVars in the parameters of the YT.Player object: {'autoplay': 0, 'controls': 0, 'showinfo': 0, 'rel': 0, playlist ': [' 9HPiBJBCOq8 ',' Mp4D0oHEnjc ',' 8y1D8KGtHfQ ',' jEEF_50sBrI ']},

Also implemented volume control buttons
 <button id="volume" onclick="editVolume ();"></button> 
- when pressed, turns on or cuts down the sound Used methods by analogy:
 /**/ function editVolume () { if (player.getVolume() == 0) { player.setVolume('100'); } else { player.setVolume('0'); } } 

And also the quality

 <button id="qual" onclick="editQuality ();">   480</button> 


 /**/ function editQuality () { player.setPlaybackQuality('medium'); document.getElementById('quality').innerHTML = '480'; } 

And fullscreen
 <button id="full" onclick="playFullscreen ();">FullScreen</button> 

 function playFullscreen (){ player.playVideo(); var requestFullScreen = iframe.requestFullScreen || iframe.mozRequestFullScreen || iframe.webkitRequestFullScreen; if (requestFullScreen) { requestFullScreen.bind(iframe)(); } } 


Here are briefly described the functions for the performance of the panel. As a result, the Play, Pause buttons, there is a playlist download button from 3 videos, Next and Back for a playlist, a fader and download line, updated time, buttons that demonstrate volume, quality and fullscreen - all this is the initial information for developing your own player interacting with Youtube iframe.

Demo version available here

When writing this article, a manual from Youtube was used in which you can find an extended description of working with Youtube iframe API here

Resources implementing such a player




Conclusion


In general, the article provides one example of creating your own player that transmits Youtube videos on your site using Javascript.

Source: https://habr.com/ru/post/306726/


All Articles