youtube api- part 1

13
Page 1 YouTube API- part 1 Written by Sandro Alberti; [email protected] Sandro is a Web designer/developer who enjoys educating others about design, both in theory and practice. INTRODUCTION This document is an overview of the ways in which you can embed and control the YouTube video player on your own Web site. Look out for 'part 2', where we will review the YouTube Data API in depth. PLAYER LOOK AND FEEL If its owner has allowed it, any YouTube video can be embedded in your Web site, in one of 3 ways: ------ 1. As a Flash object: (by default, this is an Actionscript2 Flash object) This is called either 'embedded player' or 'chromeless player' (depending on whether the Youtube controls are visible or not). Its basic look-and-feel is controlled by parameters in the Flash object (the full list can be found in appendix A). The basic code structure of an 'embedded player' is: <object width="425" height="344"> <param name="movie" value="http://www.youtube.com/v/VIDEO_ID"</param> <embed src="http://www.youtube.com/v/VIDEO_ID" type="application/x-shockwave-flash" width="425" height="344"> </embed> </object> ... where VIDEO_ID is replaced with the unique id of your YouTube video. In order to show a 'chromeless player', you can change the url slightly: from: http://www.youtube.com/v/VIDEO_ID to: http://www.youtube.com/apiplayer?video_id=VIDEO_ID You could also hide the YouTube controls in an 'embedded player' (to make it look like a 'chromeless player'): All you need to do is define a 'controls' <parameter> as 0, and add controls=0 to the <embed> tag: <param name="controls" value="0"> <embed src="http://www.youtube.com/v/VIDEO_ID" type="application/x-shockwave-flash" controls="0" width="425" height="344"> The same procedure applies to any of the other parameters. For example, to have video annotations to be shown by default, define the 'iv_load_policy' <parameter> as 1, and add controls=1 to the <embed> tag: <param name="iv_load_policy" value="1"> <embed src="http://www.youtube.com/v/VIDEO_ID" type="application/x-shockwave-flash" iv_load_policy="1" width="425" height="344">

Upload: sandro-alberti

Post on 11-Mar-2016

232 views

Category:

Documents


8 download

DESCRIPTION

This document is an overview of the ways in which you can embed and control the YouTube video player on your own Web site. Look out for 'part 2', where we will review the YouTube Data API in depth.

TRANSCRIPT

Page 1

YouTube API- part 1 Written by Sandro Alberti; [email protected] Sandro is a Web designer/developer who enjoys educating others about design, both in theory and practice.

INTRODUCTION This document is an overview of the ways in which you can embed and control the YouTube video player on your own Web site. Look out for 'part 2', where we will review the YouTube Data API in depth. PLAYER LOOK AND FEEL If its owner has allowed it, any YouTube video can be embedded in your Web site, in one of 3 ways: ------ 1. As a Flash object: (by default, this is an Actionscript2 Flash object) This is called either 'embedded player' or 'chromeless player' (depending on whether the Youtube controls are visible or not). Its basic look-and-feel is controlled by parameters in the Flash object (the full list can be found in appendix A). The basic code structure of an 'embedded player' is: <object width="425" height="344"> <param name="movie" value="http://www.youtube.com/v/VIDEO_ID"</param> <embed src="http://www.youtube.com/v/VIDEO_ID" type="application/x-shockwave-flash" width="425" height="344"> </embed> </object> ... where VIDEO_ID is replaced with the unique id of your YouTube video. In order to show a 'chromeless player', you can change the url slightly: from: http://www.youtube.com/v/VIDEO_ID to: http://www.youtube.com/apiplayer?video_id=VIDEO_ID You could also hide the YouTube controls in an 'embedded player' (to make it look like a 'chromeless player'): All you need to do is define a 'controls' <parameter> as 0, and add controls=0 to the <embed> tag: <param name="controls" value="0"> <embed src="http://www.youtube.com/v/VIDEO_ID" type="application/x-shockwave-flash" controls="0" width="425" height="344"> The same procedure applies to any of the other parameters. For example, to have video annotations to be shown by default, define the 'iv_load_policy' <parameter> as 1, and add controls=1 to the <embed> tag: <param name="iv_load_policy" value="1"> <embed src="http://www.youtube.com/v/VIDEO_ID" type="application/x-shockwave-flash" iv_load_policy="1" width="425" height="344">

Page 2

With the different parameters, among other things, you can colorize the player border and controls, determine whether the video shows on its own or in a playlist, whether it will autostart or loop or play in full-screen or high-definition, and when menus and captions should appear. Parameters are also used to 'mark' the video, to receive JavaScript commands ('playerapiid' and 'enable_js_api'; see 'JavaScript API', below) ------ 2. A YouTube player can also be shown in an iFrame: As of the writing of this document (Feb 14, 2011), this is a YouTube experimental feature; you should not yet build business-critical applications using this. In order to use it, browsers must be able to implement HTML5 postMessage (IE7 doesn't). Because it is in an iFrame, hosted by YouTube, the player can be shown as an HTML5 player rather than a Flash player for mobile devices that do not support Flash. Like the 'embedded player', the 'iFrame player' can also be controlled through JavaScript (although the JavaScript calls are not identical; see 'JavaScript API', below). The basic code structure of an 'iFrame player' is: <iframe id="player" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/VIDEO_ID?origin=example.com" frameborder="0"> ... where VIDEO_ID is replaced with the unique id of your YouTube video. frameborder is typically set to 0, in order to make the video embed more clean (but this is your choice). And, note the use of the variable 'origin=' in the url; this is a security feature to ensure that iFrame content is only shown in your domain (replace example.com with the domain of the Web page in which you're including the iFrame). ------ 3. Finally, a YouTube player can also be embedded inside of a Flash application, and controlled through Actionscript (Actionscript3; The Actionscript2 player API has been officially deprecated). This is known as an 'actionscript player'. The basic code structure of an 'actionscript player' is: // Your code must call Security.allowDomain() to communicate with your host Security.allowDomain("www.youtube.com"); // This will hold the API player instance once it is initialized. var player:Object; var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit); loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3")); function onLoaderInit(event:Event):void { addChild(loader); loader.content.addEventListener("onReady", onPlayerReady); loader.content.addEventListener("onError", onPlayerError); loader.content.addEventListener("onStateChange", onPlayerStateChange); loader.content.addEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange); } function onPlayerReady(event:Event):void { // Event.data contains the event parameter, which is the Player API ID trace("player ready:", Object(event).data); // Once this event has been dispatched by the player, we can use // cueVideoById, loadVideoById, cueVideoByUrl and loadVideoByUrl // to load a particular YouTube video.

Page 3

player = loader.content; // Set appropriate player dimensions for your application player.setSize(480, 360); } function onPlayerError(event:Event):void { // Event.data contains the event parameter, which is the error code trace("player error:", Object(event).data); } function onPlayerStateChange(event:Event):void { // Event.data contains the event parameter, which is the new player state trace("player state:", Object(event).data); } function onVideoPlaybackQualityChange(event:Event):void { // Event.data contains the event parameter, which is the new video quality trace("video quality:", Object(event).data); } JAVASCRIPT API With JavaScript, you can play-stop-pause videos, seek to a specific time in the video, modify volume and player size and video quality, and change URL. ------ Embedded players: YouTube recommends using SWFObject to embed any players that will be accessed using the JavaScript API. Embedded players can be created, run-time, through JavaScript that populates a div with a given id. For example, if you have a div with id="myytplayer", JavaScript can turn it into an embedded player: <script type="text/javascript" src="swfobject.js"></script> <script type="text/javascript"> var params = { allowScriptAccess: "always" }; var atts = { id: "myytplayer" }; swfobject.embedSWF("http://www.youtube.com/e/VIDEO_ID?enablejsapi=1&playerapiid=yt", "ytapiplayer", "425", "356", "8", null, null, params, atts); </script>

Note how this works: The allowScriptAccess parameter in the code is needed to allow the player SWF to call functions on the containing HTML page, since the player is hosted on a different domain from the HTML page. The rest is the way SWFObject is structured: swfobject.embedSWF(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) (find out more about SWFObject here: http://code.google.com/p/swfobject/) In order to use JavaScript with 'embedded players', you must define 'enable_js_api' (to be able to use JavaScript) as well as 'playerapiid' (unique id to be able to use JavaScript). Once the player is ready, it will call onYouTubePlayerReady. In order to start controlling the player through JavaScript, the first step is to reference to the player, through getElementById(): function onYouTubePlayerReady(playerId) { ytplayer = document.getElementById("myytplayer"); }

Page 4

You can now call functions using the player reference. For example, if you wanted to play the video when a user clicked a link, it would look like this: function play() { if (ytplayer) { ytplayer.playVideo(); } } <a href="javascript:void(0);" onclick="play();">Play</a> Or simply: <a href="javascript:ytplayer.playVideo()">Play</a> You can also detect events and react to them with functions (such as on StateChange-- which is when the player changes between unstarted ended playing paused buffering or video-cued): function onYouTubePlayerReady(playerId) { ytplayer = document.getElementById("myytplayer"); ytplayer.addEventListener("onStateChange", "onytplayerStateChange"); } function onytplayerStateChange(newState) { ... }

Apart from onStateChange, other events that can be captured are onPlaybackQualityChange and onError (the full list can be found in appendix B). ------ Iframe players: We have seen that iFrame players can be created with this code: <iframe id="player" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/VIDEO_ID?origin=example.com" frameborder="0">

They can also be created, run-time, through JavaScript that populates a div with a given id. For example, if you have a div with id="player', JavaScript can turn it into an iFrame player (and preparing to run 2 JavaScript functions, when the video shows 2 events: onReady -- player has finished loading and is ready to begin receiving API calls -- and onStateChange -- player changes between unstarted ended playing paused buffering or video-cued): var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { height: '390', width: '640', videoId: 'VIDEO_ID', events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); }

Page 5

And of course, in this case, we also need the 2 functions: function onPlayerReady(event) { ... } function onPlayerStateChange(event) { ... } Apart from onReady and onStateChange, other events that can be captured are onPlaybackQualityChange and onError (the full list can be found in appendix B). USEFUL LINKS YouTube-Code Youtube JavaScript API YouTube Actionscript API

Page 6

APPENDIX A: PARAMETERS autohide

Values: 0, 1, and 2 (default). This parameter indicates whether the video controls will automatically hide after a video begins playing. The default behavior is for the video progress bar to fade out while the player controls (play button, volume control, etc.) remain visible.

• If this parameter is set to 0, the video progress bar and the video player controls will be visible throughout the video.

• If this parameter is set to 1, then the video progress bar and the player controls will slide out of view a couple of seconds after the video starts playing. They will only reappear if the user moves her mouse over the video player or presses a key on her keyboard.

autoplay Values: 0 or 1. Default is 0. Sets whether or not the initial video will autoplay when the player loads.

border Values: 0 or 1. Default is 0. Setting to 1 enables a border around the entire video player. The border's primary color can be set via the color1 parameter, and a secondary color can be set by the color2 parameter.

cc_load_policy Values: 1. Default is based on user preference. Setting to 1 will cause closed captions to be shown by default, even if the user has turned captions off.

color1, color2 Values: Any RGB value in hexadecimal format. color1 is the primary border color, and color2 is the video control bar background color and secondary border color.

controls Values: 0 or 1. Default is 1. This parameter indicates whether the video player controls will display. If this parameter is set to 0, then the player controls will not display, causing the player to look like the chromeless player.

disablekb Values: 0 or 1. Default is 0. Setting to 1 will disable the player keyboard controls. Keyboard controls are as follows: Spacebar: Play / Pause Arrow Left: Jump back 10% in the current video Arrow Right: Jump ahead 10% in the current video Arrow Up: Volume up Arrow Down: Volume Down

egm Values: 0 or 1. Default is 0. Setting to 1 enables the "Enhanced Genie Menu". This behavior causes the genie menu (if present) to appear when the user's mouse enters the video display area, as opposed to only appearing when the menu button is pressed. Note: This parameter is not supported in the AS3 embedded player.

enablejsapi Values: 0 or 1. Default is 0. Setting this to 1 will enable the Javascript API. For more information on the Javascript API and how to use it, see the JavaScript API documentation.

Page 7

fs

Values: 0 or 1. Default is 0. Setting to 1 enables the fullscreen button in the embedded player and does not affect the chromeless player. The fullscreen option will not work if you load the YouTube player into another SWF. Note that you must include some extra arguments to your embed code for this to work. The bold text in the following example is required to enable fullscreen functionality: <object width="425" height="344"> <param name="movie" value="http://www.youtube.com/v/u1zgFlCw8Aw?fs=1"</param> <param name="allowFullScreen" value="true"></param> <param name="allowScriptAccess" value="always"></param> <embed src="http://www.youtube.com/v/u1zgFlCw8Aw?fs=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="425" height="344"> </embed> </object>

hd Values: 0 or 1. Default is 0. Setting to 1 enables HD playback by default. This has no effect on the Chromeless Player. This also has no effect if an HD version of the video is not available. If you enable this option, keep in mind that users with a slower connection may have an sub-optimal experience unless they turn off HD. You should ensure your player is large enough to display the video in its native resolution. Note: The AS3 player will automatically play the version of the video that is appropriate for your player's size. If an HD version of a video is available in the AS3 player and that is the appropriate version for your player, then that is the version that will play.

iv_load_policy Values: 1 or 3. Default is 1. Setting to 1 will cause video annotations to be shown by default, whereas setting to 3 will cause video annotation to not be shown by default.

loop Values: 0 or 1. Default is 0. In the case of a single video player, a setting of 1 will cause the player to play the initial video again and again. In the case of a playlist player (or custom player), the player will play the entire playlist and then start again at the first video. Note: This parameter has limited support in the AS3 player and in IFrame embeds, which could load either the AS3 or HTML5 player. Currently, the loop parameter only works in the AS3 player when used in conjunction with the playlist parameter. To loop a single video, set the loop parameter value to 1 and set the playlist parameter value to the same video ID already specified in the Player API URL: http://www.youtube.com/v/VIDEO_ID?version=3&loop=1&playlist=VIDEO_ID

origin This parameter provides an extra security measure for the IFrame API and is only supported for IFrame embeds. If you are using the IFrame API, which means you are setting the enablejsapi parameter value to 1, you should always specify your domain as the origin parameter value.

playerapiid Value can be any alphanumeric string. This setting is used in conjunction with the JavaScript API. See the JavaScript API documentation for details.

Page 8

playlist

Value is a comma-separated list of video IDs to play. If you specify a value, the first video that plays will be the VIDEO_ID specified in the URL path, and the videos specified in the playlist parameter will play thereafter.

rel Values: 0 or 1. Default is 1. Sets whether the player should load related videos once playback of the initial video starts. Related videos are displayed in the "genie menu" when the menu button is pressed. The player search functionality will be disabled if rel is set to 0.

showinfo Values: 0 or 1. Default is 1. Setting to 0 causes the player to not display information like the video title and uploader before the video starts playing.

showsearch Values: 0 or 1. Default is 1. Setting to 0 disables the search box from displaying when the video is minimized. Note that if the rel parameter is set to 0 then the search box will also be disabled, regardless of the value of showsearch.

start Values: A positive integer. This parameter causes the player to begin playing the video at the given number of seconds from the start of the video. Note that similar to the seekTo function, the player will look for the closest keyframe to the time you specify. This means sometimes the play head may seek to just before the requested time, usually no more than ~2 seconds.

Page 9

APPENDIX B: EVENTS onStateChange

This event is fired whenever the player's state changes. Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5). When the SWF is first loaded it will broadcast an unstarted (-1) event. When the video is cued and ready to play it will broadcast a video cued event (5).

onPlaybackQualityChange This event is fired whenever the video playback quality changes. For example, if you call the setPlaybackQuality(suggestedQuality) function, this event will fire if the playback quality actually changes. Your code should respond to the event and should not assume that the quality will automatically change when the setPlaybackQuality(suggestedQuality) function is called. Similarly, your code should not assume that playback quality will only change as a result of an explicit call to setPlaybackQuality or any other function that allows you to set a suggested playback quality. The value that the event broadcasts is the new playback quality. Possible values are "small", "medium", "large", "hd720", "hd1080", and "highres".

onError This event is fired when an error in the player occurs. The possible error codes are 2, 100, 101, and 150:

• The 2 error code is broadcast when a request contains an invalid parameter. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.

• The 100 error code is broadcast when the video requested is not found. This occurs when a video has been removed (for any reason), or it has been marked as private.

• The 101 error code is broadcast when the video requested does not allow playback in the embedded players.

• The error code 150 is the same as 101, it's just 101 in disguise!

onReady This event is fired when the player is loaded and initialized, meaning it is ready to receive API calls.

Page 10

APPENDIX C: JAVASCRIPT CALLS A full explanation of these is found in the Youtube JavaScript API online.

Queueing

player.cueVideoById(videoId:String, startSeconds:Number, suggestedQuality:String):Void player.loadVideoById(videoId:String, startSeconds:Number, suggestedQuality:String):Void player.cueVideoByUrl(mediaContentUrl:String, startSeconds:Number):Void player.loadVideoByUrl(mediaContentUrl:String, startSeconds:Number):Void

Playing a video

player.playVideo():Void player.pauseVideo():Void player.stopVideo():Void player.seekTo(seconds:Number, allowSeekAhead:Boolean):Void player.clearVideo():Void

Changing the player volume

player.mute():Void player.unMute():Void player.isMuted():Boolean

player.setVolume(volume:Number):Void player.getVolume():Number

Setting the player size

player.setSize(width:Number, height:Number):Void

Playback status

player.getVideoBytesLoaded():Number player.getVideoBytesTotal():Number player.getVideoStartBytes():Number player.getPlayerState():Number player.getCurrentTime():Number

Page 11

Playback quality

player.getPlaybackQuality():String player.setPlaybackQuality(suggestedQuality:String):Void player.getAvailableQualityLevels():Array

Retrieving video information

player.getDuration():Number player.getVideoUrl():String player.getVideoEmbedCode():String

Adding an event listener

player.addEventListener(event:String, listener:String):Void

Page 12

APPENDIX D: ACTIONSCRIPT CALLS A full explanation of these is found in the YouTube Actionscript API online.

Queueing

player.cueVideoById(videoId:String, startSeconds:Number, suggestedQuality:String):Void player.loadVideoById(videoId:String, startSeconds:Number, suggestedQuality:String):Void player.cueVideoByUrl(mediaContentUrl:String, startSeconds:Number):Void player.loadVideoByUrl(mediaContentUrl:String, startSeconds:Number):Void

Playing a video

player.playVideo():Void player.pauseVideo():Void player.stopVideo():Void player.seekTo(seconds:Number, allowSeekAhead:Boolean):Void

Changing the player volume

player.mute():Void player.unMute():Void

player.isMuted():Boolean player.setVolume(volume:Number):Void player.getVolume():Number

Setting the player size

player.setSize(width:Number, height:Number):Void

Playback status

player.getVideoBytesLoaded():Number player.getVideoBytesTotal():Number player.getVideoStartBytes():Number player.getPlayerState():Number player.getCurrentTime():Number

Page 13

Playback quality

player.getPlaybackQuality():String player.setPlaybackQuality(suggestedQuality:String):Void player.getAvailableQualityLevels():Array

Retrieving video information

player.getDuration():Number player.getVideoUrl():String player.getVideoEmbedCode():String

Adding an event listener

player.addEventListener(event:String, listener:Function):Void

Special functions (Actionscript-specific)

player.destroy():Void