YouTube Player API Reference for iframe Embeds

IFrame Player API 可讓您在網站中嵌入 YouTube 影片播放器,並使用 JavaScript 控製播放器。

您可以使用 API 的 JavaScript 函式,將影片加入播放、播放、暫停或停止播放、調整播放器音量,或擷取正在播放之影片的相關資訊。您也可以新增會監聽特定玩家事件的事件監聽器,例如變更玩家狀態。

本指南說明如何使用 IFrame API。可識別 API 可傳送的不同事件類型,並說明如何編寫事件監聽器來回應這些事件。其中也詳細說明瞭可以用來控制影片播放器的各種 JavaScript 函式,以及可用來進一步自訂播放器的播放器參數。

需求條件

使用者的瀏覽器必須支援 HTML5 postMessage 功能。大多數新式瀏覽器都支援 postMessage

內嵌播放器的可視區域必須至少為 200 x 200 像素。如果播放器顯示控制項,其大小必須足以完整顯示控制項,且不會縮小到最小尺寸以下的畫面。我們建議 16:9 播放器的寬度至少 480 像素,高度至少 270 像素。

任何使用 IFrame API 的網頁也必須導入下列 JavaScript 函式:

  • onYouTubeIframeAPIReady – API 會在網頁下載播放器 API 的 JavaScript 後呼叫此函式,方便您在網頁上使用 API。因此,這個函式會建立要在網頁載入時要顯示的播放器物件。

開始說明

以下 HTML 網頁範例會建立嵌入式播放器,該播放器會載入影片並播放 6 秒,然後停止播放。範例下方的清單將說明 HTML 編號。

<!DOCTYPE html>
<html>
  <body>
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="player"></div>

    <script>
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');

      tag.src = "https://www.youtube.com/iframe_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 onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          playerVars: {
            'playsinline': 1
          },
          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>

下方清單提供了以上範例的更多詳細資訊:

  1. 本節中的 <div> 標記會識別 IFrame API 將在此頁面中放置影片播放器的位置。「載入影片播放器」一節所述的玩家物件的建構函式會透過其 id 來識別 <div> 標記,以確保 API 將 <iframe> 放置在適當的位置。具體來說,IFrame API 會將 <div> 標記替換成 <iframe> 標記。

    或者,您也可以直接將 <iframe> 元素直接放在網頁上。方法請見「載入影片播放器」一節。

  2. 這部分的程式碼會載入 IFrame Player API JavaScript 程式碼。此範例使用 DOM 修改來下載 API 程式碼,以確保程式碼能夠以非同步方式擷取。(如同 Stack Overflow 解答中所述,部分新式瀏覽器目前仍不支援 <script> 標記的 async 屬性 (這項功能也支援非同步下載)。

  3. onYouTubeIframeAPIReady 函式會在玩家 API 程式碼下載後立即執行。程式碼的這個部分定義了全域變數 player,也就是您要嵌入的影片播放器,該函式接著會建構影片播放器物件。

  4. onReady 事件觸發時,系統會執行 onPlayerReady 函式。在這個範例中,函式表示影片播放器準備就緒後,應該就會開始播放。

  5. API 會在玩家的狀態變更時呼叫 onPlayerStateChange 函式,這可能表示玩家正在播放、暫停、結束等。該函式表示在玩家狀態為 1 (播放) 時,玩家應播放六秒,然後呼叫 stopVideo 函式來停止影片。

正在載入影片播放器

API 的 JavaScript 程式碼載入後,API 會呼叫 onYouTubeIframeAPIReady 函式,此時您可以建構 YT.Player 物件來在網頁中插入影片播放器。以下的 HTML 摘錄是上例中的 onYouTubeIframeAPIReady 函式:

var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '390',
    width: '640',
    videoId: 'M7lc1UVf-VE',
    playerVars: {
      'playsinline': 1
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

影片播放器的建構函式會指定下列參數:

  1. 第一個參數可指定 DOM 元素或 HTML 元素的 id,API 會插入內含播放器的 <iframe> 標記。

    IFrame API 會將指定元素替換為包含播放器的 <iframe> 元素。如果你替換的元素具有與插入的 <iframe> 元素不同的顯示樣式,可能會影響網頁的版面配置。根據預設,<iframe> 會顯示為 inline-block 元素。

  2. 第二個參數是指定播放器選項的物件。這個物件包含下列屬性:
    • width (數字) - 影片播放器的寬度。預設值為 640
    • height (數字) - 影片播放器的高度。預設值為 390
    • videoId (字串):用於識別播放器將載入的 YouTube 影片 ID。
    • playerVars (物件) – 物件的屬性可識別可用於自訂播放器的播放器參數
    • events (物件) – 物件的屬性可識別 API 觸發的事件,以及 API 會在這些事件發生時呼叫的函式 (事件監聽器)。在範例中,建構函式表示 onPlayerReady 函式會在 onReady 事件觸發時執行,而 onPlayerStateChange 函式會在 onStateChange 事件觸發時執行。

入門指南 一節所述,您不用自行在網頁中插入空白的 <div> 元素,播放器 API 的 JavaScript 程式碼會取代 <iframe> <iframe> 標記。「範例」一節的第一個範例就說明瞭如何進行這項作業。

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

請注意,如果您確實寫入 <iframe> 標記,那麼當您建構 YT.Player 物件時,就不需要指定以 <iframe> 標記屬性 (或 src 網址中指定的 videoId 和播放器參數) 的 widthheight 的值。為保障安全性,您也必須在網址中加入 origin 參數,並將網址架構 (http://https://) 和代管網頁的完整網域指定為參數值。雖然 origin 為選用功能,但可防止系統在第三方網頁中植入惡意第三方 JavaScript,進而防止 YouTube 播放器遭到盜用。

「範例」區段還提供幾個範例來建構影片播放器物件。

作業套件

如要呼叫玩家 API 方法,您必須先取得要控制的播放器物件參照。只要在本文件的開始使用載入影片播放器章節中,建立 YT.Player 物件以取得參考。

Functions

佇列函式

佇列功能可讓您載入及播放影片、播放清單或其他影片清單。如果您使用下方所述的物件語法來呼叫這些函式,那麼您也可以將使用者上傳的影片清單排入佇列或載入清單。

API 支援兩種呼叫佇列函式的語法。

  • 引數語法需要依照指定順序列出函式引數。

  • 物件語法可讓您將物件做為單一參數傳遞,並為想要設定的函式引數定義物件屬性。此外,該 API 可能支援引數語法不支援的額外功能。

舉例來說,loadVideoById 函式可透過下列其中一種方式呼叫。請注意,物件語法不支援引數語法不支援的 endSeconds 屬性。

  • 引數語法

    loadVideoById("bHQqvYy5KYo", 5, "large")
  • 物件語法

    loadVideoById({'videoId': 'bHQqvYy5KYo',
                   'startSeconds': 5,
                   'endSeconds': 60});

影片的待播函式

cueVideoById
  • 引數語法

    player.cueVideoById(videoId:String,
                        startSeconds:Number):Void
  • 物件語法

    player.cueVideoById({videoId:String,
                         startSeconds:Number,
                         endSeconds:Number}):Void

這個函式會載入指定影片的縮圖,讓播放器播放影片。在呼叫 playVideo()seekTo() 之前,播放器不會要求 FLV。

  • 必要的 videoId 參數會指定要播放影片的 YouTube 影片 ID。在 YouTube Data API 中,video 資源的 id 屬性會指定 ID。
  • 選用的 startSeconds 參數接受浮點值/整數,並指定呼叫 playVideo() 時影片應開始播放的時間。如果您指定 startSeconds 值,然後呼叫 seekTo(),則播放器會從 seekTo() 呼叫中指定的時間播放。當影片可供提示且可供播放時,播放器會播送 video cued 事件 (5)。
  • 選用的 endSeconds 參數 (僅支援物件語法) 接受浮點值/整數,且指定呼叫 playVideo() 時影片應停止播放的時間。如果您指定 endSeconds 值,然後呼叫 seekTo()endSeconds 值就會失效。

loadVideoById

  • 引數語法

    player.loadVideoById(videoId:String,
                         startSeconds:Number):Void
  • 物件語法

    player.loadVideoById({videoId:String,
                          startSeconds:Number,
                          endSeconds:Number}):Void

這個函式會載入並播放指定的影片。

  • 必要的 videoId 參數會指定要播放影片的 YouTube 影片 ID。在 YouTube Data API 中,video 資源的 id 屬性會指定 ID。
  • 選用的 startSeconds 參數可接受浮點值/整數。如果有指定,影片會從最近的主要畫面格開始播放到指定時間。
  • 選用的 endSeconds 參數可接受浮點值/整數。如果有指定,影片會在指定時間停止播放。

cueVideoByUrl

  • 引數語法

    player.cueVideoByUrl(mediaContentUrl:String,
                         startSeconds:Number):Void
  • 物件語法

    player.cueVideoByUrl({mediaContentUrl:String,
                          startSeconds:Number,
                          endSeconds:Number}):Void

這個函式會載入指定影片的縮圖,讓播放器播放影片。在呼叫 playVideo()seekTo() 之前,播放器不會要求 FLV。

  • 必要的 mediaContentUrl 參數會指定完整的 YouTube 播放器網址,格式為 http://www.youtube.com/v/VIDEO_ID?version=3
  • 選用的 startSeconds 參數接受浮點值/整數,並指定呼叫 playVideo() 時影片應開始播放的時間。如果您指定 startSeconds,然後呼叫 seekTo(),則播放器會從 seekTo() 呼叫中指定的時間播放。當影片可供提示且可供播放時,播放器會播送 video cued 事件 (5)。
  • 選用的 endSeconds 參數 (僅支援物件語法) 接受浮點值/整數,且指定呼叫 playVideo() 時影片應停止播放的時間。如果您指定 endSeconds 值,然後呼叫 seekTo()endSeconds 值就會失效。

loadVideoByUrl

  • 引數語法

    player.loadVideoByUrl(mediaContentUrl:String,
                          startSeconds:Number):Void
  • 物件語法

    player.loadVideoByUrl({mediaContentUrl:String,
                           startSeconds:Number,
                           endSeconds:Number}):Void

這個函式會載入並播放指定的影片。

  • 必要的 mediaContentUrl 參數會指定完整的 YouTube 播放器網址,格式為 http://www.youtube.com/v/VIDEO_ID?version=3
  • 選用的 startSeconds 參數接受浮點值/整數,並指定影片開始播放的時間點。如果指定 startSeconds (數字可以浮點),影片會從最近的主要畫面格開始,到指定的時間點開始。
  • 選用的 endSeconds 參數 (僅支援物件語法) 接受浮點值/整數,並指定影片應停止播放的時間。

佇列的函式佇列

cuePlaylistloadPlaylist 函式可讓您載入及播放播放清單。如果您使用物件語法呼叫這些函式,您也可以將使用者上傳的影片清單排入 (或載入) 清單。

由於這些函式的運作方式會依使用引數語法或物件語法來呼叫而定,因此以下將說明這兩種呼叫方法。

cuePlaylist
  • 引數語法

    player.cuePlaylist(playlist:String|Array,
                       index:Number,
                       startSeconds:Number):Void
    將指定的播放清單排入佇列。播放清單被收錄並準備播放時,玩家將播送 video cued 活動 (5)。
    • 必要的 playlist 參數會指定一組 YouTube 影片 ID。在 YouTube Data API 中,video 資源的 id 屬性可識別該影片的 ID。

    • 選用的 index 參數會指定即將播放播放清單中第一部影片的索引。該參數使用零索引,預設參數值為 0,因此預設行為是載入並播放播放清單中的第一部影片。

    • 選用的 startSeconds 參數接受浮點值/整數,並指定呼叫 playVideo() 函式時,播放清單中第一部影片開始播放的時間。如果您指定 startSeconds 值,然後呼叫 seekTo(),則播放器會從 seekTo() 呼叫中指定的時間播放。如果您將播放清單收錄為播放清單,然後呼叫 playVideoAt() 函式,播放器就會在指定影片的開頭開始播放。

  • 物件語法

    player.cuePlaylist({listType:String,
                        list:String,
                        index:Number,
                        startSeconds:Number}):Void
    將指定影片清單排入佇列。這份清單可以是播放清單或使用者上傳影片的資訊提供。將搜尋結果清單排入佇列的功能已淘汰,自 2020 年 11 月 15 日起將不再支援。

    當清單被提示且準備播放時,玩家將播送 video cued 活動 (5)。

    • 選用的 listType 屬性會指定您要擷取的結果資訊提供類型。有效值為 playlistuser_uploads。自 2020 年 11 月 15 日起,系統不再支援 search 的值。預設值為 playlist

    • list 必要屬性含有索引鍵,用於識別 YouTube 應傳回的特定影片清單。

      • 如果 listType 屬性值是 playlist,則 list 屬性會指定播放清單 ID 或影片 ID 陣列。在 YouTube Data API 中,playlist 資源的 id 屬性可用來識別播放清單的 ID,而 video 資源的 id 屬性則可用來指定影片 ID。
      • 如果 listType 屬性值是 user_uploads,則 list 屬性可識別哪些使用者將傳回上傳影片。
      • 如果 listType 屬性值是 search,則 list 屬性會指定搜尋查詢。注意:這項功能已淘汰,自 2020 年 11 月 15 日起將不再支援。

    • 選用的 index 屬性會指定清單中第一部影片要播放的索引。該參數使用零索引,預設參數值為 0,因此預設行為是載入並播放清單中第一部影片。

    • 選用的 startSeconds 屬性接受浮點值/整數,並指定呼叫 playVideo() 函式時,清單中第一部影片開始播放的時間。如果您指定 startSeconds 值,然後呼叫 seekTo(),則播放器會從 seekTo() 呼叫中指定的時間播放。如果您在提示清單後呼叫 playVideoAt() 函式,播放器會在指定影片的開頭開始播放。

loadPlaylist
  • 引數語法

    player.loadPlaylist(playlist:String|Array,
                        index:Number,
                        startSeconds:Number):Void
    這個函式會載入並播放指定的播放清單。
    • 必要的 playlist 參數會指定一組 YouTube 影片 ID。在 YouTube Data API 中,video 資源的 id 屬性會指定影片 ID。

    • 選用的 index 參數會指定即將播放播放清單中第一部影片的索引。該參數使用零索引,預設參數值為 0,因此預設行為是載入並播放播放清單中的第一部影片。

    • 選用的 startSeconds 參數接受浮點值/整數,並指定播放清單中第一部影片開始播放的時間。

  • 物件語法

    player.loadPlaylist({list:String,
                         listType:String,
                         index:Number,
                         startSeconds:Number}):Void
    這個函式會載入並播放指定的清單。這份清單可以是播放清單或使用者上傳影片的資訊提供。載入搜尋結果清單的功能已淘汰,自 2020 年 11 月 15 日起將不再支援。
    • 選用的 listType 屬性會指定您要擷取的結果資訊提供類型。有效值為 playlistuser_uploads。自 2020 年 11 月 15 日起,系統不再支援 search 的值。預設值為 playlist

    • list 必要屬性含有索引鍵,用於識別 YouTube 應傳回的特定影片清單。

      • 如果 listType 屬性值是 playlist,則 list 屬性會指定播放清單 ID 或影片 ID 陣列。在 YouTube Data API 中,playlist 資源的 id 屬性會指定播放清單的 ID,而 video 資源的 id 屬性會指定影片 ID。
      • 如果 listType 屬性值是 user_uploads,則 list 屬性可識別哪些使用者將傳回上傳影片。
      • 如果 listType 屬性值是 search,則 list 屬性會指定搜尋查詢。注意:這項功能已淘汰,自 2020 年 11 月 15 日起將不再支援。

    • 選用的 index 屬性會指定清單中第一部影片要播放的索引。該參數使用零索引,預設參數值為 0,因此預設行為是載入並播放清單中第一部影片。

    • 選用的 startSeconds 屬性接受浮點值/整數,並指定清單中第一部影片開始播放的時間。

播放控制項和播放器設定

播放影片

player.playVideo():Void
播放目前提示/載入的影片。此函式執行之後的最終播放器狀態會是 playing (1)。

注意:只有在影片中的播放器播放按鈕啟用時,播放次數才會計入影片的官方觀看次數。
player.pauseVideo():Void
暫停目前正在播放的影片。除非在呼叫函式時玩家處於 ended (0) 狀態,否則執行該函式後的最終玩家狀態會是 paused (2),在此情況下,玩家狀態將維持不變。
player.stopVideo():Void
停止並停止載入目前的影片。如果您知道使用者不會因此在播放器中觀看其他影片,建議您保留這項功能。如果您要暫停影片,只需呼叫 pauseVideo 函式即可。如果您想變更玩家正在播放的影片,可以先呼叫其中一個佇列函式,然後再呼叫 stopVideo

重要事項:有別於 pauseVideo 函式能讓玩家進入 paused (2) 狀態,stopVideo 函式可以將玩家設為任何非遊戲狀態,包括 ended (0)、paused (2)、video cued (5) 或 unstarted (-1)。
player.seekTo(seconds:Number, allowSeekAhead:Boolean):Void
跳轉到影片中的指定時間。如果播放器在呼叫函式時設為暫停,其會維持暫停狀態。如果系統從其他狀態 (playingvideo cued 等) 呼叫此函式,播放器將會播放影片。
  • seconds 參數可識別玩家應提前的時間。

    在該時間點之前,播放器會前進至最接近的主要畫面格,除非播放器已下載使用者想要尋找的影片片段。

  • 如果 seconds 參數指定的時間超出目前緩衝處理的影片資料的時間,allowSeekAhead 參數可判斷播放器是否會向伺服器發出新的要求。

    我們建議您在使用者沿著影片進度列拖曳滑鼠時,將這個參數設為 false,然後在使用者放開滑鼠時,將這個參數設為 true。這個方法可讓使用者捲動瀏覽影片中超過無緩衝點的多個影片片段,而不需要請求新的影片串流。當使用者放開滑鼠按鈕時,播放器會指向影片中的特定時間點,並視需要請求新的影片串流。

控制 360 度影片播放

注意:360° 影片播放功能僅支援行動裝置。在不支援的裝置上,360° 影片會出現變形,而且您無法以任何方式變更觀看視角,包括透過 API 使用方向感應器、使用方向感應器,或是回應裝置拖曳/拖曳的動作。

player.getSphericalProperties():Object
擷取能描述影片播放目前視角或視圖的屬性。此外:
  • 這個物件只用於 360 度影片,也就是球型影片。
  • 如果目前的影片不是 360 度影片,或者系統透過不支援的裝置呼叫該函式,則函式會傳回空白物件。
  • 在支援的行動裝置上,如果 enableOrientationSensor 屬性設為 true,則此函式會傳回 fov 屬性包含正確值且其他屬性設為 0 的物件。
該物件包含以下屬性:
屬性
yaw 範圍 [0, 360) 中的數字,代表視圖的視圖水平角度 (以度為單位),代表使用者將檢視畫面轉向更靠左或向右的角度。朝向等長方形投影的影片中心會呈現中立位置,代表 0°,這個值會隨著觀眾離開而增加。
pitch 範圍為 [-90, 90] 的一個數字,用來表示檢視區塊垂直角度的角度 (以度為單位),代表使用者調整檢視的向上或向下視角。影片方向以等距的矩形投影為中心,代表的是 0°,這個值會隨著觀眾查詢而增加。
roll [-180, 180] 範圍內的數字,代表檢視畫面的順時針或逆時針旋轉角度 (以度為單位)。中性位置,等距矩形中的水平軸與檢視畫面的水平軸平行,代表 0°。這個值會隨著檢視畫面順時針旋轉,而隨著檢視畫面逆時針旋轉而降低。

請注意,嵌入式播放器並未提供調整畫面滾動功能的使用者介面。您可以透過下列任一方式並單獨使用擲骰子:
  1. 使用行動瀏覽器中的方向感應器提供視圖的捲軸。如果啟用方向感應器,則 getSphericalProperties 函式一律會傳回 0 做為 roll 屬性的值。
  2. 如果方向感應器已停用,請使用這個 API 將擲骰子的值設為非零值。
fov 範圍 [30, 120] 中的數字,代表沿著可視區域長邊測量的視野 (以度為單位)。較短的邊緣會自動調整成與檢視畫面的長寬比成正比。

預設值為 100 度。降低數值,就如同放大影片內容一樣;提高價值則與縮小。您可以使用 API 調整這個值,也可以在影片進入全螢幕模式時,使用滑鼠滾輪進行調整。
player.setSphericalProperties(properties:Object):Void
設定播放 360 度影片的影片方向。(如果目前的影片不是球形形式,那麼無論輸入的內容為何,此方法都屬於免人工管理)。

播放器檢視畫面會更新,以回應 properties 物件中任何已知屬性值。檢視畫面會保留該物件未包含的任何其他已知屬性值。

此外:
  • 如果物件含有不明和/或非預期的屬性,播放器會忽略這些屬性。
  • 如本節開頭所述,並非所有行動裝置都支援 360 度影片播放功能。
  • 根據預設,在支援的行動裝置上,此函式只會設定 fov 屬性,並不會影響 yawpitchroll 屬性 (360° 影片播放)。詳情請參閱下方的 enableOrientationSensor 屬性。
傳遞至函式的 properties 物件包含下列屬性:
屬性
yaw 請參閱上方的定義
pitch 請參閱上方的定義
roll 請參閱上方的定義
fov 請參閱上方的定義
enableOrientationSensor 注意:這個屬性只會影響受支援裝置的 360° 觀看體驗。這個布林值值表示 IFrame 嵌入是否應回應支援裝置螢幕方向 (例如行動瀏覽器的 DeviceOrientationEvent) 信號變更的事件。預設參數值為 true

支援的行動裝置
  • 當值為 true 時,內嵌播放器只會依裝置移動,調整 360 度影片播放的 yawpitchroll 屬性。不過,fov 屬性仍可透過 API 變更,且 API 實際上是在行動裝置上變更 fov 屬性的唯一方法。此為預設行為。
  • 當值為 false時,裝置的移動不會影響 360° 的觀看體驗,並且必須透過 API 設定 yawpitchrollfov 屬性。

不支援的行動裝置
enableOrientationSensor 屬性值對播放體驗沒有任何影響。

在播放清單中播放影片

player.nextVideo():Void
這個函式會載入並播放播放清單中的下一部影片。
  • 如果在觀看播放清單中的最後一部影片時呼叫 player.nextVideo(),且播放清單設定為持續播放 (loop),則播放器會載入並播放清單中第一部影片。

  • 如果在觀看播放清單中的最後一部影片時呼叫 player.nextVideo(),且播放清單並未連續播放,系統就會結束播放。

player.previousVideo():Void
這個函式會載入並播放播放清單中的上一部影片。
  • 如果在觀看播放清單中的第一部影片時呼叫 player.previousVideo(),且播放清單設定為持續播放 (loop),則播放器會載入並播放清單中的最後一個影片。

  • 如果在觀看播放清單中的第一部影片時呼叫 player.previousVideo(),且播放清單並未設為繼續播放,播放器會從頭重新開始播放第一部影片。

player.playVideoAt(index:Number):Void
這個函式會載入並播放播放清單中的指定影片。
  • 必要的 index 參數會指定要在播放清單中播放的影片索引。這個參數使用零索引,因此 0 的值可識別清單中的第一個影片。如果您已隨機播放播放清單,這個函式會在隨機播放的播放清單中以特定位置播放影片。

調整玩家音量

player.mute():Void
將播放器設為靜音。
player.unMute():Void
將播放器取消靜音。
player.isMuted():Boolean
如果播放器遭到靜音,則傳回 true,如未傳回,則傳回 false
player.setVolume(volume:Number):Void
設定音量。接受介於 0100 之間的整數。
player.getVolume():Number
傳回玩家目前的音量,也就是 0100 之間的整數。請注意,即使播放器已設為靜音,getVolume() 仍會傳回音量。

設定播放器大小

player.setSize(width:Number, height:Number):Object
設定包含播放器的 <iframe> 的大小 (以像素為單位)。

設定播放速率

player.getPlaybackRate():Number
這個函式會擷取目前播放影片的播放速率。預設的播放速率為 1,表示影片播放正常。播放速率可能包含 0.250.511.52 等值。
player.setPlaybackRate(suggestedRate:Number):Void
這個函式會設定目前影片的建議播放速率。如果播放速率有變動,只有已收錄或播放過的影片會變更。如果您設定提示影片的播放速率,當呼叫 playVideo 函式或使用者直接從播放器控制項啟動播放功能時,該比率仍然有效。此外,如果呼叫函式來呼叫或載入影片或播放清單 (cueVideoByIdloadVideoById 等),系統會將播放速率重設為 1

呼叫這個函式並不保證播放速率一定會發生變化。不過,如果播放速率發生變更,就會觸發 onPlaybackRateChange 事件,且您的程式碼應回應事件,而非呼叫 setPlaybackRate 函式的情形。

getAvailablePlaybackRates 方法會傳回目前播放影片的可能播放速率。但是,如果您將 suggestedRate 參數設為不支援的整數或浮點值,播放器會將該值無條件捨去至最接近的支援值,並依照 1 的方向進行。
player.getAvailablePlaybackRates():Array
這個函式會傳回目前影片可用的播放速率組合。預設值為 1,表示影片正常播放。

這個函式會傳回數字陣列,其中按播放速度由低至高排序。即使玩家不支援可變播放速度,陣列也至少須包含一個值 (1)。

設定播放清單的播放行為

player.setLoop(loopPlaylists:Boolean):Void

此函式可指明影片播放器是否應持續播放播放清單,或是否應在播放清單中的最後一部影片結束後繼續播放。預設行為是播放清單不會循環播放。

即使您載入或選取其他播放清單,這項設定仍會維持不變。也就是說,如果載入播放清單,呼叫值為 truesetLoop 函式,然後載入第二個播放清單,第二個播放清單也會循環播放。

必要的 loopPlaylists 參數可識別循環行為。

  • 如果參數值為 true,影片播放器就會持續播放播放清單。播放播放清單中最後一部影片之後,影片播放器會回到播放清單的開頭並再次播放。

  • 如果參數值為 false,則影片播放器會在播放清單中播放最後一部影片後結束播放。

player.setShuffle(shufflePlaylist:Boolean):Void

這個函式可指明是否要隨機調整播放清單中的影片順序,以便播放順序與播放清單創作者指定的順序不同。如果你在開始播放的播放清單中隨機播放一份清單,系統就會在播放中的影片重新排序後,再次播放這份清單中的項目。然後根據重新排序的清單選擇接下來播放的影片。

如果您載入或收錄其他播放清單,這項設定不會改變。也就是說,如果您載入播放清單、呼叫 setShuffle 函式,然後載入第二個播放清單,第二個播放清單就不會被隨機播放。

必要的 shufflePlaylist 參數指示 YouTube 是否應隨機播放播放清單。

  • 如果參數值為 true,YouTube 就會隨機調整播放清單的順序。如果您指示函式隨機播放一份已隨機播放的播放清單,YouTube 將會再次調整順序。

  • 如果參數值為 false,YouTube 就會將播放清單的順序變更為原始順序。

播放狀態

player.getVideoLoadedFraction():Float
傳回介於 01 之間的數字,用於指定播放器顯示為緩衝的影片百分比。這個方法會傳回比目前已淘汰的 getVideoBytesLoadedgetVideoBytesTotal 方法更可靠的數字。
player.getPlayerState():Number
傳回播放器的狀態。可能的值包括:
  • -1 – 尚未開始
  • 0 – 已結束
  • 1 – 播放中
  • 2 – 已暫停
  • 3 – 緩衝處理中
  • 5 – 提示的影片
player.getCurrentTime():Number
傳回影片開始播放後經過的時間 (以秒為單位)。
player.getVideoStartBytes():Number
已於 2012 年 10 月 31 日淘汰。傳回影片檔案開始載入的位元組數。(這個方法現在一律會傳回 0 的值)。
player.getVideoBytesLoaded():Number
已於 2012 年 7 月 18 日淘汰。請改用 getVideoLoadedFraction 方法來判定已緩衝的影片百分比。

這個方法會傳回介於 01000 之間的值,用來估算已載入的影片數量。只要將 getVideoBytesLoaded 值除以 getVideoBytesTotal 值,即可算出已載入影片的分數。
player.getVideoBytesTotal():Number
已於 2012 年 7 月 18 日淘汰。請改用 getVideoLoadedFraction 方法來判定已緩衝的影片百分比。

傳回目前載入/播放影片的影片大小,或影片近似值。

此方法一律會傳回 1000 的值。只要將 getVideoBytesLoaded 值除以 getVideoBytesTotal 值,即可算出已載入影片的分數。

擷取影片資訊

player.getDuration():Number
傳回目前播放影片的時間,以秒為單位。請注意,getDuration() 會傳回 0,直到影片的中繼資料載入為止 (通常會在影片開始播放後發生)。

如果目前正在播放的影片是現場直播getDuration() 函式會傳回自影片串流開始後經過的時間。具體來說,這是指影片在未重設或中斷的情況下串流播放的時間。此外,這個時間長度通常比實際事件時間還長,因為串流可能會在活動開始時間之前開始執行。
player.getVideoUrl():String
傳回目前載入/播放影片的 YouTube.com 網址。
player.getVideoEmbedCode():String
傳回目前載入/播放影片的嵌入程式碼。

擷取播放清單資訊

player.getPlaylist():Array
這個函式會依序傳回播放清單中的影片 ID。根據預設,這個函式會按播放清單擁有者指定的順序傳回影片 ID。不過,如果您呼叫了 setShuffle 函式以隨機排序播放清單順序,則 getPlaylist() 函式的傳回值會反映出隨機排序的順序。
player.getPlaylistIndex():Number
這個函式會傳回目前正在播放的播放清單影片索引。
  • 如果您未隨機播放播放清單,則傳回值將指出播放清單建立者放置影片的位置。傳回值使用零索引,因此 0 的值可識別播放清單中的第一部影片。

  • 隨機播放這個播放清單時,傳回值將會識別影片在隨機播放清單中的順序。

新增或移除事件監聽器

player.addEventListener(event:String, listener:String):Void
為指定的 event 新增事件監聽器函式。下方的「事件」部分會列出玩家可能觸發的不同事件。事件監聽器是字串,用於指定在指定事件啟動時會執行的函式。
player.removeEventListener(event:String, listener:String):Void
移除指定 event 的事件監聽器函式。listener 這個字串可識別指定事件觸發時不會執行的函式。

存取及修改 DOM 節點

player.getIframe():Object
這個方法會傳回內嵌 <iframe> 的 DOM 節點。
player.destroy():Void
移除包含播放器的 <iframe>

活動

API 會觸發事件,以通知您的應用程式已嵌入內嵌播放器。如上一節所述,您可以在建構 YT.Player 物件時新增事件監聽器,藉此訂閱事件。此外,您也可以使用 addEventListener 函式。

API 會將事件物件做為各個引數的唯一引數傳遞給這些函式。這個事件物件包含下列屬性:

  • 事件的 target 可識別與事件相對應的影片播放器。
  • 事件的 data 會指定與事件相關的值。請注意,onReady 事件不會指定 data 屬性。

下列清單定義 API 觸發的事件:

onReady
只要玩家載入完成且準備開始接收 API 呼叫,就會觸發這個事件。如果您要在玩家準備就緒後,自動執行特定作業 (例如播放影片或顯示影片相關資訊),就應該實作此功能。

下方範例的函式範例可處理這個事件。API 傳遞至函式的事件物件具有識別玩家的 target 屬性。這個函式會擷取目前所載入影片的嵌入程式碼,然後開始播放影片,並在 id 值的 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
每當玩家的狀態變更時,就會觸發這個事件。 API 傳遞至事件監聽器函式的事件物件 data 屬性將會指定對應新玩家狀態的整數。可能的值包括:

  • -1 (尚未開始)
  • 0 (已結束)
  • 1 (播放中)
  • 2 (暫停)
  • 3 (緩衝處理中)
  • 5 (提示影片)。

當播放器初次載入影片時,系統會廣播 unstarted (-1) 事件。當影片在可用且可供播放時,播放器就會播送 video cued (5) 事件。您可在程式碼中指定整數值,或使用下列其中一個命名空間變數:

  • YT.PlayerState.ENDED
  • YT.PlayerState.PLAYING
  • YT.PlayerState.PAUSED
  • YT.PlayerState.BUFFERING
  • YT.PlayerState.CUED

onPlaybackQualityChange
每當影片播放品質發生變化時,就會引發這個事件。這可能表示觀眾的播放環境發生變化。如要進一步瞭解影響播放條件或可能導致事件觸發的因素,請前往 YouTube 說明中心

API 傳遞至事件監聽器函式的事件物件 data 屬性值會是字串,可用來識別新的播放品質。 可能的值包括:

  • small
  • medium
  • large
  • hd720
  • hd1080
  • highres

onPlaybackRateChange
每當影片播放率發生變化,就會觸發這個事件。舉例來說,如果您呼叫 setPlaybackRate(suggestedRate) 函式,且播放速率實際上發生變化,就會觸發此事件。呼叫 setPlaybackRate(suggestedRate) 函式時,應用程式不應回應事件,且不應假設播放率會自動變更。同樣地,您的程式碼不應假設只有在明確呼叫 setPlaybackRate 時,影片播放頻率才會變更。

API 傳遞至事件監聽器函式的事件物件 data 屬性值是一個數字,用來識別新的播放速率。getAvailablePlaybackRates 方法會傳回目前提示或播放影片的有效播放速率清單。
onError
如果播放器發生錯誤,就會觸發這個事件。 API 會將 event 物件傳遞至事件監聽器函式。該物件的 data 屬性會指定整數,以識別發生的錯誤類型。 可能的值包括:

  • 2 - 要求含有無效的參數值。舉例來說,如果您指定的影片 ID 沒有 11 個字元,或是影片 ID 包含無效字元 (例如驚嘆號或星號),就會發生這個錯誤。
  • 5 – 要求的內容無法在 HTML5 播放器中播放,或是發生與 HTML5 播放器相關的其他錯誤。
  • 100 - 找不到你要求的影片。如果影片遭移除 (不論原因為何) 或遭標示為私人影片,就會發生這個錯誤。
  • 101 - 要求的影片擁有者不允許在嵌入式播放器中播放影片。
  • 150 - 這個錯誤與 101 相同。這種錯誤僅發生 101 錯誤!
onApiChange
此事件會啟動,表示播放器已載入 (或卸載) 含公開 API 方法的模組。您的應用程式可以監聽此事件,然後輪詢玩家以判斷最近載入的模組有哪些選項。之後,您的應用程式就可以擷取或更新這些選項的現有設定。

下列指令會擷取可設定播放器選項的模組名稱陣列:
player.getOptions();
目前您只能設定選項的模組是 captions 模組,可處理播放器的隱藏式輔助字幕。收到 onApiChange 事件後,您的應用程式可使用下列指令來決定要為 captions 模組設定哪些選項:
player.getOptions('captions');
透過此指令對玩家進行輪詢後,您可以確認您要存取的選項確實可以存取。下列指令會擷取及更新模組選項:
Retrieving an option:
player.getOption(module, option);

Setting an option
player.setOption(module, option, value);
下表列出 API 支援的選項:

模組 選項 說明
captions 字型大小 這個選項可調整播放器顯示的字幕字型大小。

有效值包括 -10123。預設大小為 0,最小尺寸為 -1。如果將這個選項設為低於 -1 的整數,將顯示最小的字幕大小,而將這個選項設為大於 3 的整數時,將會顯示最大的字幕大小。
captions 重新載入 這個選項會載入正在播放的影片隱藏式輔助字幕資料。如果擷取該選項的值,該值為 null。將值設為 true 即可重新載入字幕資料。

行動裝置注意事項

自動播放與腳本播放

就某些行動瀏覽器 (例如 Chrome 和 Safari) 而言,HTML5 <video> 元素只允許由使用者互動 (例如輕觸播放器) 來播放。以下是 Apple 說明文件的摘錄:

「警告:為避免因使用者付費而透過行動網路進行下載,iOS 裝置上的 Safari 無法自動播放嵌入式媒體,且使用者一律會開始播放影片。」

基於這項限制,函式和參數 (例如 autoplayplayVideo()loadVideoById()) 無法在所有行動環境中運作。

範例

正在建立 YT.Player 物件

  • 範例 1:搭配現有 <iframe> 使用 API

    在這個範例中,網頁上的 <iframe> 元素已定義將用於使用這個 API 的播放器。請注意,播放器的 src 網址必須將 enablejsapi 參數設為 1,或者 <iframe> 元素的 enablejsapi 屬性必須設為 true

    onPlayerReady 函式會在玩家準備就緒後,將播放器周圍的邊框顏色變更為橘色。接著,onPlayerStateChange 函式會根據目前玩家的狀態來變更玩家周圍的邊框顏色。例如,玩家播放時顏色是綠色、暫停時為紅色,緩衝處理時為藍色,依此類推。

    本例使用以下程式碼:

    <iframe id="existing-iframe-example"
            width="640" height="360"
            src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
            frameborder="0"
            style="border: solid 4px #37474F"
    ></iframe>
    
    <script type="text/javascript">
      var tag = document.createElement('script');
      tag.id = 'iframe-demo';
      tag.src = 'https://www.youtube.com/iframe_api';
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('existing-iframe-example', {
            events: {
              'onReady': onPlayerReady,
              'onStateChange': onPlayerStateChange
            }
        });
      }
      function onPlayerReady(event) {
        document.getElementById('existing-iframe-example').style.borderColor = '#FF6D00';
      }
      function changeBorderColor(playerStatus) {
        var color;
        if (playerStatus == -1) {
          color = "#37474F"; // unstarted = gray
        } else if (playerStatus == 0) {
          color = "#FFFF00"; // ended = yellow
        } else if (playerStatus == 1) {
          color = "#33691E"; // playing = green
        } else if (playerStatus == 2) {
          color = "#DD2C00"; // paused = red
        } else if (playerStatus == 3) {
          color = "#AA00FF"; // buffering = purple
        } else if (playerStatus == 5) {
          color = "#FF6DOO"; // video cued = orange
        }
        if (color) {
          document.getElementById('existing-iframe-example').style.borderColor = color;
        }
      }
      function onPlayerStateChange(event) {
        changeBorderColor(event.data);
      }
    </script>
    
  • 範例 2:播放中斷

    此範例建立 1280 x 720 像素的影片播放器。然後,onReady 事件的事件監聽器會呼叫 setVolume 函式,將音量調整為最高設定。

    function onYouTubeIframeAPIReady() {
      var player;
      player = new YT.Player('player', {
        width: 1280,
        height: 720,
        videoId: 'M7lc1UVf-VE',
        events: {
          'onReady': onPlayerReady,
          'onStateChange': onPlayerStateChange,
          'onError': onPlayerError
        }
      });
    }
    
    function onPlayerReady(event) {
      event.target.setVolume(100);
      event.target.playVideo();
    }
    
  • 範例 3:這個範例設定播放器參數,以便在載入時自動播放影片,並隱藏影片播放器的控制項。也會針對 API 廣播的多個事件新增事件監聽器。

    function onYouTubeIframeAPIReady() {
      var player;
      player = new YT.Player('player', {
        videoId: 'M7lc1UVf-VE',
        playerVars: { 'autoplay': 1, 'controls': 0 },
        events: {
          'onReady': onPlayerReady,
          'onStateChange': onPlayerStateChange,
          'onError': onPlayerError
        }
      });
    }

控制 360 度影片

本例使用以下程式碼:

<style>
  .current-values {
    color: #666;
    font-size: 12px;
  }
</style>
<!-- The player is inserted in the following div element -->
<div id="spherical-video-player"></div>

<!-- Display spherical property values and enable user to update them. -->
<table style="border: 0; width: 640px;">
  <tr style="background: #fff;">
    <td>
      <label for="yaw-property">yaw: </label>
      <input type="text" id="yaw-property" style="width: 80px"><br>
      <div id="yaw-current-value" class="current-values"> </div>
    </td>
    <td>
      <label for="pitch-property">pitch: </label>
      <input type="text" id="pitch-property" style="width: 80px"><br>
      <div id="pitch-current-value" class="current-values"> </div>
    </td>
    <td>
      <label for="roll-property">roll: </label>
      <input type="text" id="roll-property" style="width: 80px"><br>
      <div id="roll-current-value" class="current-values"> </div>
    </td>
    <td>
      <label for="fov-property">fov: </label>
      <input type="text" id="fov-property" style="width: 80px"><br>
      <div id="fov-current-value" class="current-values"> </div>
    </td>
    <td style="vertical-align: bottom;">
      <button id="spherical-properties-button">Update properties</button>
    </td>
  </tr>
</table>

<script type="text/javascript">
  var tag = document.createElement('script');
  tag.id = 'iframe-demo';
  tag.src = 'https://www.youtube.com/iframe_api';
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var PROPERTIES = ['yaw', 'pitch', 'roll', 'fov'];
  var updateButton = document.getElementById('spherical-properties-button');

  // Create the YouTube Player.
  var ytplayer;
  function onYouTubeIframeAPIReady() {
    ytplayer = new YT.Player('spherical-video-player', {
        height: '360',
        width: '640',
        videoId: 'FAtdv94yzp4',
    });
  }

  // Don't display current spherical settings because there aren't any.
  function hideCurrentSettings() {
    for (var p = 0; p < PROPERTIES.length; p++) {
      document.getElementById(PROPERTIES[p] + '-current-value').innerHTML = '';
    }
  }

  // Retrieve current spherical property values from the API and display them.
  function updateSetting() {
    if (!ytplayer || !ytplayer.getSphericalProperties) {
      hideCurrentSettings();
    } else {
      let newSettings = ytplayer.getSphericalProperties();
      if (Object.keys(newSettings).length === 0) {
        hideCurrentSettings();
      } else {
        for (var p = 0; p < PROPERTIES.length; p++) {
          if (newSettings.hasOwnProperty(PROPERTIES[p])) {
            currentValueNode = document.getElementById(PROPERTIES[p] +
                                                       '-current-value');
            currentValueNode.innerHTML = ('current: ' +
                newSettings[PROPERTIES[p]].toFixed(4));
          }
        }
      }
    }
    requestAnimationFrame(updateSetting);
  }
  updateSetting();

  // Call the API to update spherical property values.
  updateButton.onclick = function() {
    var sphericalProperties = {};
    for (var p = 0; p < PROPERTIES.length; p++) {
      var propertyInput = document.getElementById(PROPERTIES[p] + '-property');
      sphericalProperties[PROPERTIES[p]] = parseFloat(propertyInput.value);
    }
    ytplayer.setSphericalProperties(sphericalProperties);
  }
</script>

修訂版本記錄

April 27, 2021

The Getting Started and Loading a Video Player sections have been updated to include examples of using a playerVars object to customize the player.

October 13, 2020

Note: This is a deprecation announcement for the embedded player functionality that lets you configure the player to load search results. This announcement affects the IFrame Player API's queueing functions for lists, cuePlaylist and loadPlaylist.

This change will become effective on or after 15 November 2020. After that time, calls to the cuePlaylist or loadPlaylist functions that set the listType property to search will generate a 4xx response code, such as 404 (Not Found) or 410 (Gone). This change also affects the list property for those functions as that property no longer supports the ability to specify a search query.

As an alternative, you can use the YouTube Data API's search.list method to retrieve search results and then load selected videos in the player.

October 24, 2019

The documentation has been updated to reflect the fact that the API no longer supports functions for setting or retrieving playback quality. As explained in this YouTube Help Center article, to give you the best viewing experience, YouTube adjusts the quality of your video stream based on your viewing conditions.

The changes explained below have been in effect for more than one year. This update merely aligns the documentation with current functionality:

  • The getPlaybackQuality, setPlaybackQuality, and getAvailableQualityLevels functions are no longer supported. In particular, calls to setPlaybackQuality will be no-op functions, meaning they will not actually have any impact on the viewer's playback experience.
  • The queueing functions for videos and playlists -- cueVideoById, loadVideoById, etc. -- no longer support the suggestedQuality argument. Similarly, if you call those functions using object syntax, the suggestedQuality field is no longer supported. If suggestedQuality is specified, it will be ignored when the request is handled. It will not generate any warnings or errors.
  • The onPlaybackQualityChange event is still supported and might signal a change in the viewer's playback environment. See the Help Center article referenced above for more information about factors that affect playback conditions or that might cause the event to fire.

May 16, 2018

The API now supports features that allow users (or embedders) to control the viewing perspective for 360° videos:

  • The getSphericalProperties function retrieves the current orientation for the video playback. The orientation includes the following data:
    • yaw - represents the horizontal angle of the view in degrees, which reflects the extent to which the user turns the view to face further left or right
    • pitch - represents the vertical angle of the view in degrees, which reflects the extent to which the user adjusts the view to look up or down
    • roll - represents the rotational angle (clockwise or counterclockwise) of the view in degrees.
    • fov - represents the field-of-view of the view in degrees, which reflects the extent to which the user zooms in or out on the video.
  • The setSphericalProperties function modifies the view to match the submitted property values. In addition to the orientation values described above, this function supports a Boolean field that indicates whether the IFrame embed should respond to DeviceOrientationEvents on supported mobile devices.

This example demonstrates and lets you test these new features.

June 19, 2017

This update contains the following changes:

  • Documentation for the YouTube Flash Player API and YouTube JavaScript Player API has been removed and redirected to this document. The deprecation announcement for the Flash and JavaScript players was made on January 27, 2015. If you haven't done so already, please migrate your applications to use IFrame embeds and the IFrame Player API.

August 11, 2016

This update contains the following changes:

  • The newly published YouTube API Services Terms of Service ("the Updated Terms"), discussed in detail on the YouTube Engineering and Developers Blog, provides a rich set of updates to the current Terms of Service. In addition to the Updated Terms, which will go into effect as of February 10, 2017, this update includes several supporting documents to help explain the policies that developers must follow.

    The full set of new documents is described in the revision history for the Updated Terms. In addition, future changes to the Updated Terms or to those supporting documents will also be explained in that revision history. You can subscribe to an RSS feed listing changes in that revision history from a link in that document.

June 29, 2016

This update contains the following changes:

  • The documentation has been corrected to note that the onApiChange method provides access to the captions module and not the cc module.

June 24, 2016

The Examples section has been updated to include an example that demonstrates how to use the API with an existing <iframe> element.

January 6, 2016

The clearVideo function has been deprecated and removed from the documentation. The function no longer has any effect in the YouTube player.

December 18, 2015

European Union (EU) laws require that certain disclosures must be given to and consents obtained from end users in the EU. Therefore, for end users in the European Union, you must comply with the EU User Consent Policy. We have added a notice of this requirement in our YouTube API Terms of Service.

April 28, 2014

This update contains the following changes:

March 25, 2014

This update contains the following changes:

  • The Requirements section has been updated to note that embedded players must have a viewport that is at least 200px by 200px. If a player displays controls, it must be large enough to fully display the controls without shrinking the viewport below the minimum size. We recommend 16:9 players be at least 480 pixels wide and 270 pixels tall.

July 23, 2013

This update contains the following changes:

  • The Overview now includes a video of a 2011 Google I/O presentation that discusses the iframe player.

October 31, 2012

This update contains the following changes:

  • The Queueing functions section has been updated to explain that you can use either argument syntax or object syntax to call all of those functions. Note that the API may support additional functionality in object syntax that the argument syntax does not support.

    In addition, the descriptions and examples for each of the video queueing functions have been updated to reflect the newly added support for object syntax. (The API's playlist queueing functions already supported object syntax.)

  • When called using object syntax, each of the video queueing functions supports an endSeconds property, which accepts a float/integer and specifies the time when the video should stop playing when playVideo() is called.

  • The getVideoStartBytes method has been deprecated. The method now always returns a value of 0.

August 22, 2012

This update contains the following changes:

  • The example in the Loading a video player section that demonstrates how to manually create the <iframe> tag has been updated to include a closing </iframe> tag since the onYouTubeIframeAPIReady function is only called if the closing </iframe> element is present.

August 6, 2012

This update contains the following changes:

  • The Operations section has been expanded to list all of the supported API functions rather than linking to the JavaScript Player API Reference for that list.

  • The API supports several new functions and one new event that can be used to control the video playback speed:

    • Functions

      • getAvailablePlaybackRates – Retrieve the supported playback rates for the cued or playing video. Note that variable playback rates are currently only supported in the HTML5 player.
      • getPlaybackRate – Retrieve the playback rate for the cued or playing video.
      • setPlaybackRate – Set the playback rate for the cued or playing video.

    • Events

July 19, 2012

This update contains the following changes:

  • The new getVideoLoadedFraction method replaces the now-deprecated getVideoBytesLoaded and getVideoBytesTotal methods. The new method returns the percentage of the video that the player shows as buffered.

  • The onError event may now return an error code of 5, which indicates that the requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.

  • The Requirements section has been updated to indicate that any web page using the IFrame API must also implement the onYouTubeIframeAPIReady function. Previously, the section indicated that the required function was named onYouTubePlayerAPIReady. Code samples throughout the document have also been updated to use the new name.

    Note: To ensure that this change does not break existing implementations, both names will work. If, for some reason, your page has an onYouTubeIframeAPIReady function and an onYouTubePlayerAPIReady function, both functions will be called, and the onYouTubeIframeAPIReady function will be called first.

  • The code sample in the Getting started section has been updated to reflect that the URL for the IFrame Player API code has changed to http://www.youtube.com/iframe_api. To ensure that this change does not affect existing implementations, the old URL (http://www.youtube.com/player_api) will continue to work.

July 16, 2012

This update contains the following changes:

  • The Operations section now explains that the API supports the setSize() and destroy() methods. The setSize() method sets the size in pixels of the <iframe> that contains the player and the destroy() method removes the <iframe>.

June 6, 2012

This update contains the following changes:

  • We have removed the experimental status from the IFrame Player API.

  • The Loading a video player section has been updated to point out that when inserting the <iframe> element that will contain the YouTube player, the IFrame API replaces the element specified in the constructor for the YouTube player. This documentation change does not reflect a change in the API and is intended solely to clarify existing behavior.

    In addition, that section now notes that the insertion of the <iframe> element could affect the layout of your page if the element being replaced has a different display style than the inserted <iframe> element. By default, an <iframe> displays as an inline-block element.

March 30, 2012

This update contains the following changes:

  • The Operations section has been updated to explain that the IFrame API supports a new method, getIframe(), which returns the DOM node for the IFrame embed.

March 26, 2012

This update contains the following changes:

  • The Requirements section has been updated to note the minimum player size.