суббота, 23 апреля 2011 г.

YouTube Player API Reference for <iframe> Embeds (Experimental )


Important: This is an experimental feature, which means that it might change unexpectedly.

Overview

Note: The IFrame player API described in this document is an experimental feature that represents the next stage of YouTube Player APIs. You should not yet build business-critical applications using this API nor should you launch any applications using this API into a production environment.

While you can access an early version of the API now, anticipate that functionality may change as support for new functions will certainly be added while support for existing functions may change or disappear.

Please share any feedback that you may have about the API in the Developer Forum.

The IFrame player API lets you embed a YouTube video player on your website and control the player using JavaScript. Unlike the Flash and JavaScript player APIs, which both involve embedding a Flash object on your web page, the IFrame API posts content to an <iframe> tag on your page. This approach provides more flexibility than the previously available APIs since it allows YouTube to serve an HTML5 player rather than a Flash player for mobile devices that do not support Flash.

Using the API's JavaScript functions, you can queue videos for playback; play, pause, or stop those videos; adjust the player volume; or retrieve information about the video being played. You can also add event listeners that will execute in response to certain player events, such as a player state change or a video playback quality change.

This guide explains how to use the IFrame API. It identifies the different types of events that the API can send and explains how to write event listeners to respond to those events. It also details the different JavaScript functions that you can call to control the video player as well as the player parameters you can use to further customize the player.

Requirements

The end user must be using a browser that supports the HTML5 postMessage feature. Most modern browsers support postMessage, though Internet Explorer 7 does not support it.

Any web page that uses the IFrame API must also implement the following JavaScript function:

  • onYouTubePlayerAPIReady – The API will call this function when the page has finished downloading the JavaScript for the player API, which enables you to then use the API on your page. Thus, this function might create the player objects that you want to display when the page loads.

Getting started

The sample HTML page below creates an embedded player that will load a video, play it for six seconds, and then stop the playback. The numbered comments in the HTML are explained in the list below the example.

<html>   <body>     <!-- 1. The <div> tag will contain the <iframe> (and video player) -->     <div id="player"></div>      <script>       // 2. This code loads the IFrame Player API code asynchronously.       var tag = document.createElement('script');       tag.src = "http://www.youtube.com/player_api";       var firstScriptTag = document.getElementsByTagName('script')[0];       firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);        // 3. This function creates an <iframe> (and YouTube player)       //    after the API code downloads.       var player;       function onYouTubePlayerAPIReady() {         player = new YT.Player('player', {           height: '390',           width: '640',           videoId: 'u1zgFlCw8Aw',           events: {             'onReady': onPlayerReady,             'onStateChange': onPlayerStateChange           }         });       }        // 4. The API will call this function when the video player is ready.       function onPlayerReady(event) {         event.target.playVideo();       }        // 5. The API calls this function when the player's state changes.       //    The function indicates that when playing a video (state=1),       //    the player should play for six seconds and then stop.       var done = false;       function onPlayerStateChange(event) {         if (event.data == YT.PlayerState.PLAYING && !done) {           setTimeout(stopVideo, 6000);           done = true;         }       }       function stopVideo() {         player.stopVideo();       }     </script>   </body> </html> 

The following list provides more details about the sample above:

  1. The <div> tag in this section identifies the location on the page where the IFrame API will place the video player. The constructor for the player object, which is described in the Loading a video player section, identifies the <div> tag by its id to ensure that the API places the <iframe> in the proper location.

    As an alternative, you could also put the <iframe> element directly on the page. The Loading a video player section explains how to do so.

  2. The code in this section loads the IFrame Player API JavaScript code. The example uses DOM modification to download the API code to ensure that the code is retrieved asynchronously. (The <script> tag's async attribute, which also enables asynchronous downloads, is not yet supported in all modern browsers as discussed in this article.

  3. The onYouTubePlayerAPIReady function will execute as soon as the player API code downloads. This portion of the code defines a global variable, player, which refers to the video player you are embedding, and the function then constructs the video player object.

  4. The onPlayerReady function will execute when the onReady event fires. In this example, the function indicates that when the video player is ready, it should begin to play.

  5. The API will call the onPlayerStateChange function when the player's state changes, which may indicate that the player is playing, paused, finished, and so forth. The function indicates that when the player state is 1 (playing), the player should play for six seconds and then call the stopVideo function to stop the video.

Loading a video player

After the API's JavaScript code loads, the API will call the onYouTubePlayerAPIReady function, at which point you can construct a YT.Player object to insert a video player on your page. The HTML excerpt below shows the onYouTubePlayerAPIReady function from the example above:

var player; function onYouTubePlayerAPIReady() {   player = new YT.Player('player', {     height: '390',     width: '640',     videoId: 'u1zgFlCw8Aw',     events: {       'onReady': onPlayerReady,       'onStateChange': onPlayerStateChange     }   }); } 

The constructor for the video player specifies the following parameters:

  1. The first parameter specifies either the DOM element or the id of the HTML element where the API will insert the <iframe> tag containing the player.
  2. The second parameter is an object that specifies player options. The object contains the following properties:
    • width (number) – The width of the video player. The default value is 640.
    • height (number) – The height of the video player. The default value is 390.
    • videoId (string) – The YouTube video ID that identifies the video that the player will load.
    • playerVars (object) – The object's properties identify player parameters that can be used to customize the player.
    • events (object) – The object's properties identify the events that the API fires and the functions (event listeners) that the API will call when those events occur. In the example, the constructor indicates that the onPlayerReady function will execute when the onReady event fires and that the onPlayerStateChange function will execute when the onStateChange event fires.

As mentioned in the Getting started section, instead of writing an empty <div> element on your page, which the player API's JavaScript code will then replace with an <iframe> element, you could create the <iframe> tag yourself.

<iframe id="player" type="text/html" width="640" height="390"   src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1&origin=example.com"   frameborder="0">

If you do write the <iframe> tag, then when you construct the YT.Player object, you do not need to specify values for the width and height, which are specified as attributes of the <iframe> tag, or the videoId and player parameters, which are are specified in the src URL. As an extra security measure, you should also include the origin parameter to the URL, specifying your domain as the parameter value.

The Examples section shows a few more examples for constructing video player objects.

Events

The API fires events to notify your application of changes to the embedded player. As noted in the previous section, you can subscribe to events by adding an event listener when constructing the YT.Player object, and you can also use the addEventListener function.

The API will pass an event object as the sole argument to each of those functions. The event object has the following properties:

  • The event's target identifies the video player that corresponds to the event.
  • The event's data specifies a value relevant to the event. Note that the onReady event does not specify a data property.

The following list defines the events that the API fires:

onReady
This event fires whenever a player has finished loading and is ready to begin receiving API calls. Your application should implement this function if you want to automatically execute certain operations, such as playing the video or displaying information about the video, as soon as the player is ready.

The example below shows a sample function for handling this event. The event object that the API passes to the function has a target property, which identifies the player The function retrieves the embed code for the currently loaded video, starts to play the video, and displays the embed code in the page element that has an id value of embed-code.
function onPlayerReady(event) {   var embedCode = event.target.getVideoEmbedCode();   event.target.playVideo();   if (document.getElementById('embed-code')) {     document.getElementById('embed-code').innerHTML = embedCode;   } } 
onStateChange
This event fires whenever the player's state changes. The data property of the event object that the API passes to your event listener function will specify an integer that corresponds to the new player state. Possible data values are:
  • -1 (unstarted)
  • 0 (ended)
  • 1 (playing)
  • 2 (paused)
  • 3 (buffering)
  • 5 (video cued).

When the player first loads a video, it will broadcast an unstarted (-1) event. When a video is cued and ready to play, the player will broadcast a video cued (5) event. In your code, you can specify the integer values or you can use one of the following namespaced variables:
  • YT.PlayerState.ENDED
  • YT.PlayerState.PLAYING
  • YT.PlayerState.PAUSED
  • YT.PlayerState.BUFFERING
  • YT.PlayerState.CUED
onPlaybackQualityChange
This event fires 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 application 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 data property of the event object that the API passes to the event listener function will specify a string value that identifies the new playback quality. Possible values are:
  • small
  • medium
  • large
  • hd720
  • hd1080
  • highres
onError
This event fires if an error occurs in the player. The data property of the event object that the API passes to the event listener function will specify an integer that identifies the type of error that occurred. Possible values are:
  • 2 – The request contains an invalid parameter value. 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.
  • 100 – The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.
  • 101 – The owner of the requested video does not allow it to be played in embedded players.
  • 150 – This error is the same as 101. It's just a 101 error in disguise!

Operations

We intend to support a similar set of functions for the IFrame API as are currently supported for the JavaScript API. Please refer to that document for a list of functions, and note that some of those functions may not yet work in the IFrame API.

Functions that currently work include, but may not be limited to, playVideo, pauseVideo, stopVideo, setVolume, and getDuration.

Examples

Creating YT.Player objects

  • Example 1: Loud playback

    This example creates a 1280px by 720px video player. The event listener for the onReady event then calls the setVolume function to adjust the volume to the highest setting.

    function onYouTubePlayerAPIReady() {   var player;   player = new YT.Player('player', {     width: 1280,     height: 720,     videoId: 'u1zgFlCw8Aw',     events: {       'onReady': onPlayerReady,       'onPlaybackQualityChange': onPlayerPlaybackQualityChange,       'onStateChange': onPlayerStateChange,       'onError': onPlayerError     }   }); }  function onPlayerReady(event) {   event.target.setVolume(100);   event.target.playVideo(); } 
  • Example 2: This example sets player parameters to automatically play the video when it loads and to hide the video player's controls. It also adds event listeners for all of the events that the API broadcasts.

    function onYouTubePlayerAPIReady() {   var player;   player = new YT.Player('player', {     videoId: 'u1zgFlCw8Aw',     playerVars: { 'autoplay': 1, 'controls': 0 },     events: {       'onReady': onPlayerReady,       'onPlaybackQualityChange': onPlayerPlaybackQualityChange,       'onStateChange': onPlayerStateChange,       'onError': onPlayerError     }   }); }

Комментариев нет:

Отправить комментарий