4 – YOUTUBE PLAYER API

This is article 4 of the YouTube API With PHP series.

1.Using IFrame

The simplest way of putting a YouTube video in a web page is to use the IFRAME tag. This does not require any coding and works by pasting the tag with its parameters.

<html>
<head>

</head>

<body>
    <iframe id="player" type="text/html" width="640" height="390"
  src="http://www.YouTube.com/embed/0r7i8riYCe0"
  frameborder="0"></iframe>
</body>
</html>

The Output:

1

 

 

 

 

 

The IFrame takes in the following attributes:

  • width – width of the frame in pixels
  • height – height of the frame in pixels
  • src – the url of the YouTube video. This can be obtained from the YouTube URL of the video in the browser. Eg. https://www.YouTube.com/watch?v=0r7i8riYCe0 The string of characters after v= is the id of the video

The IFrame can be put statically in the page or generated dynamically via PHP and then displayed on the page.But this approach does not allow any control of the video player via javascript code. So what we need to do is call the Player API javascript library in our web page and then work with it.

Rather than put a normal <script src=…> tag in the page to call the API , YouTube recommends calling the script asynchronously.  Below is sample code which

  • loads the api script dynamically in Javascript
  • Dynamically binds the iframe to the YT-Player object
  • Allows playing,pausing and stopping of the video via Javascript

<html>
<head>

<script>

var tag = document.createElement('script');
tag.src = "//www.YouTube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player = null;

function onYouTubeIframeAPIReady() {
	player = new YT.Player('player');
}

function startPlayer() {
    if (player) {
   	  player.playVideo();   	 
    }
}

function stopPlayer() {
    if (player) {
   	  player.stopVideo();   	 
    }
}

function pausePlayer() {
    if (player) {
   	  player.pauseVideo();   	 
    }
}

</script>
</head>

<body>
    <iframe id="player" type="text/html" width="640" height="390"
  src="http://www.YouTube.com/embed/0r7i8riYCe0?enablejsapi=1"
  frameborder="0"></iframe>

  <br>
	<a href="#" onclick="startPlayer();">Play</a>
    &nbsp;&nbsp;
     <a href="#" onclick="stopPlayer();">Stop </a>
      &nbsp;&nbsp;
     <a href="#" onclick="pausePlayer();">Pause </a>

</body>
</html>

The Output:

2

 

 

 

 

 

 

 

The YT-Player object is the class which lets us control the video within the iframe.  We bind it to the iframe by passing in the id attribute of the Iframe .

Using the links we can control the player as required. For the Iframe to respond to javascript, you need to add the enablejsapi=1parameter to the src attribute .

src=”http://www.YouTube.com/embed/0r7i8riYCe0?enablejsapi=1″

If you don’t add enablejsapi=1 to the src attribute, the functions won’t work.

If you have multiple YouTube players in the same page and you want to control them, then use different variables to control them. Eg:

var player1 = null;
var player2 = null;

player1 = new YT.Player('playerA');
player2 = new YT.Player('playerB');

2.Load Playlists

You can use the Iframe tag to load a playlist instead of a single video. The only difference is the what you put in the src attribute:

src=”http://www.YouTube.com/embed/?listType=playlist&list=PLMC9KNkIncKtPzgY-5rmhvj7fax8fdxoj&enablejsapi=1

You need to put

  • listType=playlist
  • list=the playlist id (all playlist ids start with the prefix PL)

When the video is displayed you will find a menu icon at the top left of the video which expands to show the videos in the playlist. You can then choose another video , which will then start playing.

3

 

 

 

 

 

 

 

3.Load Videos of a User

The Iframe tag can also show a playlist of all the videos uploaded by a user. So for instance if you have a url like https://www.YouTube.com/user/BillyIdolVEVO  then the user’s id is the the string of characters after /user/

The src attribute of the iframe tag will become:

src=”http://www.YouTube.com/embed/?listType=user_uploads&list=BillyIdolVEVO&enablejsapi=1

The output is similar to that of using the playlist:

4

 

 

 

 

 

 

 

4.Load Search Results

You can even use the Iframe tag to show the results of a search query. A Search query can be a single word or a phrase (preferably url encoded).

The src attribute will have

  • listType=search
  • list=the search query

Eg.

src=”http://www.YouTube.com/embed/?listType=search&list=statue+of+liberty&enablejsapi=1

The output will show all the matching videos as a playlist:

5

 

 

 

 

 

 

 

4.Player Parameters

Here are a list of all the other parameters that can be used in src attribute:

  • autoplay – default value is 0. If 1 then video starts playing on load. If 0, video does not start playing.
  • cc_load_policy – default behaviour is based on the video owner’s preference. Setting it to 1 shows closed captions. Setting it to 0 will not show closed captions
  • color – default value is red. This sets the color of the progress bar in the video. The only other option is white.
  • controls – default value is 1. If set to 0, no controls are shown at the bottom of the video. If set to 1, controls show when the player loads. If set to 2, the controls only show when the video starts playing.
  • disablekb – default value is 0. Setting it to 1 will disable keyboard control of the player. Setting it to zero will enable keyboard control.
  • end – No default value. This is a time period in seconds which sets when the video should stop playing. So end=10 will stop the playing after 10 seconds .
  • fs – default value is 1. Setting it to 0 will not allow fullscreen playback. Setting it to 1 will allow fullscreen playback.
  • h1 – No default value. This sets the language preference of the caption and the player interface using the two-letter international code for language. Eg. h1=fr will set the language to French. This only works if the video has caption tracks and the video owner has allowed this capability.
  • iv_load_policy – default value is 1. Setting it to zero disables annotations to be shown by Setting it to 1 enables display of video annotations.
  • loop – default value is 0. Setting it to 1 makes the video loop from the start on reaching the end. Setting it to 0 disables looping. For a playlist, setting it to 1 will make the player play the first video after it finishes the last video.
  • modestBranding – default value is 0. Setting this to 1 disables the display of the YouTube icon in the lower right hand side of the control bar. However if the video is paused a small YouTube icon will display at the top right hand side. Setting this to 0 shows the YouTube icon in the control bar. Note: This parameter does not work reliably.
  • origin – No default value. Setting the origin to the domain in which the web page is running acts as an extra security measure. Note: This parameter may or may not work in certain browsers
  • rel – default value is 1. Setting it to 0 disables display of related videos when video stops playing. Setting it to 1 enables display of related videos.
  • showinfo – default value is 1. Setting it to 0 disables the display of the video title and uploader before the video starts playing. Setting it to 1 shows the video info before playback.
  • start – No default value. This sets the place in the video from where to start playing. The value is set in seconds. Eg.start=150 will start playback 150 seconds from the starting point.

 

The code below shows the iframe tag with the above parameters set.

<html>
<head>

<script>

var tag = document.createElement('script');
tag.src = "//www.YouTube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player = null;

function onYouTubeIframeAPIReady() {
	player = new YT.Player('player');
}

</script>
</head>

<body>
    <iframe id="player" type="text/html" width="640" height="390"
  src="http://www.YouTube.com/embed/0r7i8riYCe0?enablejsapi=1&autoplay=1&cc_load_policy=1&color=red&controls=2&disablekb=1&end=10&fs=0&h1=fr&iv_load_policy=3&loop=0&modestBranding=0&origin=localhost&rel=0&playsinline=0&showinfo=0&start=5"
  frameborder="0"></iframe>

 
</body>
</html>

Instead of specifying all parameters statically within the src attribute, you can dynamically set these parameters in pure Javascript using the YT.Player object.

<html>
<head>

<script>

var tag = document.createElement('script');
tag.src = "//www.YouTube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player = null;

function onYouTubeIframeAPIReady() {

  player = new YT.Player('player', {
      	height: '390',
      	width: '340',
      	videoId: '0r7i8riYCe0',
   	   enablejsapi:1,    
      	playerVars: {
                	autoplay: 1,
                	loop: 1,
                	controls: 0,
                	showinfo: 0,
                	autohide: 1,
                	modestbranding: 1,
                	color: 'red'},
    	});

}
</script>
</head>

<body>
    <div id="player"></div>

</body>
</html>

Note that almost all the player parameters can be set under the playerVars variable.

 

5.Player Events

The video player also has an event callback list, which enables to you to control the player when certain events are called.

An example code is given below:

<html>
<head>

<script>

var tag = document.createElement('script');
tag.src = "//www.YouTube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player = null;

function onYouTubeIframeAPIReady() {

  player = new YT.Player('player', {
      	height: '390',
      	width: '340',
      	videoId: '0r7i8riYCe0',
   	   enablejsapi:1,    
   		events: {
        	'onReady': function (event) { console.log("onready"); },
        	'onStateChange': function (event) { console.log("onstatechange"); }
      	}
   	   
 });

}
</script>
</head>

<body>
    <div id="player"></div>

</body>
</html>

 

Each event which we want to control is listed under the events variable in the YT.Player constructor. We can either run a function within the constructor itself as shown above or we can pass the name of a function which is defined elsewhere in the page.

A complete list of the available functions is given below.

● onReady – when player has loaded and is ready for API access
● onStateChange – The following are the state change constants passed in the function argument:
○ – 1 player has loaded a video but not started
○ 0 player has stopped playing
○ 1 player is playing
○ 2 player is paused
○ 3 player is buffering
○ 5 player is assigned a video id to be played
● onPlaybackQualityChange – called when a user changes the video quality. The following string values are passed in the function argument:
○ small
○ Medium
○ large
○ hd720
○ hd1080
○ Highres
● onPlaybackRateChange – called if a new playback rate is set by user or through code, but only if the new rate is valid for the video. If the new rate is not valid for the video, this event is not called. The function argument passes a number as the suggested playback rate. The getAvailablePlaybackRates() function gives a list of the valid playback rates for the video
● onError – called if the player has an error. The function argument will have one of the following values:
○ 2 – invalid parameter value
○ 5 – the HTML5 player cannot be loaded or the HTML5 player had an error.
○ 100 – video requested was not found – either it is deleted or is marked private
○ 101 – the video has not been allowed to be played in an embedded player by the video owner
○ 150 – same as 101
● onApiChange – Not really useful at the moment

 

6.Player Methods

 Given below is is the list of methods which can be called on the YT.Player object:

  • playVideo() – play current video. No return value.
  • pauseVideo() – pause current video. No return value.
  • stopVideo() – stop current video. No return value
  • seekTo(seconds: integer, allowSeekAhead: boolean) – This will have no effect if the player is in a paused state. No return value.
    • the seconds argument will set the time in seconds from the start , from which the video will start playing.
    • allowSeekAhead when set to true forces the player to request data from the server is the portion of the video is not in the buffer.
  • nextVideo() – loads the next video in the playlist. If current video is last in the playlist and loop is set to false then the current video ends playing. If loop is true, then the first video starts playing. No return value.
  • previousVideo() – loads the previous video in the playlist. If current video is first in the playlist and loop is set to false then the current video ends playing. If loop is true, then the last video starts playing. No return value.
  • playVideoAt(index: number) – plays a video at the index position in the playlist. The first video starts from zero. No return value;
  • mute() – mute the player. No return value
  • unMute() – unmute the player. No return value;
  • isMuted() – Returns true if muted else false
  • setVolume(volume: number) – Sets a volume level between 0 to 100. No return value;
  • getVolume() – Returns the volume in a range of 0 to 100. This works even if the video is muted.
  • setSize(width:number, height:number) – set the width and height of the iframe that contains the player ,in pixels. No return value.
  • getPlaybackRate() – returns a decimal or integer as the current playback rate. Default value returned is 1 which means normal playback rate. Other playback rates are relative to 1 eg.0.25 mean its playing at 25% of the normal playback rate. 2 means its playing at twice the normal rate. No return value.
  • setPlaybackRate(suggestedRate: number) – See getPlaybackRate for possible values. It is not necessary that the rate will take effect. If it takes effect that the onPlaybackRateChange event is fired. No return value.
  • getAvailablePlaybackRates() – returns an array of numbers sorted from slowest to fastest speeds. The array will always have the default value of 1, even if no other values are present.
  • setLoop(loopPlaylists:boolean). Default value is 0. Setting it to 1, will make playlists loop. This setting persists even when loading different playlists. No return value.
  • setShuffle(shufflePlaylist: boolean) – Default value is 0. Setting it to 1 shuffles the videos in the current playlist in a random order. This will work even if a video is playing in the playlist. This setting does not persist across different playlists. Loading a new playlist will set this value back to 0. No return value;
  • getVideoLoadedFraction() – returns a floating number between 0.0 and 1.0 which shows how much of the video has been loaded into the player. Eg. 0.2 would mean 20%.
  • getPlayerState() – returns one of the following numbers:
    • -1 unstarted
    • 0 ended
    • 1 playing
    • 2 paused
    • 3 buffering
    • 5 video cued
  • getCurrentTime() – returns the number of seconds that the video has played from the starting point.
  • getPlaybackQuality() – Returns one of the following string values:
    • highres
    • hd1080
    • hd720
    • large
    • medium
    • small
  • setPlaybackQuality(suggestedQuality:string) – assigns a suggested quality to the current video. It is not guaranteed that the quality will change if the video does not support it. If it works then onPlaybackQualityChange event is fired. No return value. Possible values are:
    • highres
    • hd1080
    • hd720
    • large
    • medium
    • Small
  • getAvailableQualityLevels() – returns an array with string values sorted from lowest to highest quality. Only works if a video is loaded in the player. See getPlaybackQuality() for possible values
  • getDuration() – returns the number of seconds the current video has completed playing
  • getVideoUrl() – returns the current video URL as a string
  • getVideoEmbedCode() – returns the current video’s embed code as a string
  • getPlaylist() – returns an array of the video ids in the current playlist. This will return them in the order as they were added by the playlist owner. If setShuffle is set then it will return the ids in the shuffled order.
  • getPlaylistIndex() – returns a number which denotes the index of the currently playing video in the playlist. The index starts from 0. If the playlist is shuffled, it will reflect the shuffled order
  • getIframe() – returns the Javascript DOM node for the parent IFRAME node
  • destroy() – removes the parent IFRAME node from the Javascript DOM elements.

 

3 Comments

  1. @Gachi as far as I know, the controls toggle is executed at the time of initialization of the player. I am not sure if it can be controlled without recreating the player instance again.

Leave a Reply

Your email address will not be published.


*