YouTube Player API Reference for iframe Embeds

IFrame 播放器 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 範例網頁建立的嵌入式播放器都能載入影片,並播放六秒,然後停止播放。下方清單說明瞭 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. 玩家 API 程式碼下載後,onYouTubeIframeAPIReady 函式就會立即執行。此部分程式碼會定義 player 全域變數,參照您要嵌入的影片播放器,然後由函式建構影片播放器物件。

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

  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 物件時,就不需要指定 widthheight 的值 (指定為 <iframe> 標記的屬性),或指定 videoId 和玩家參數 (在 src 網址中指定的)。為加強安全措施,您應該在網址中加入 origin 參數,並指定網址配置 (http://https://) 以及代管網頁的完整網域做為參數值。雖然 origin 是選用項目,但可以防止惡意第三方 JavaScript 植入你的網頁,以及防止 YouTube 播放器入侵。

「範例」部分還會顯示其他建構影片播放器物件的範例。

作業套件

若要呼叫播放器 API 方法,您必須先取得要控制的玩家物件的參照。只要按照本文件的「入門」和「載入影片播放器」這兩節所述,建立 YT.Player 物件即可取得參照。

函式

將函式排入佇列

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

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 參數應以 http://www.youtube.com/v/VIDEO_ID?version=3 格式指定完整的 YouTube 播放器網址。
  • 選用的 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 參數應以 http://www.youtube.com/v/VIDEO_ID?version=3 格式指定完整的 YouTube 播放器網址。
  • 選用的 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) 狀態,與 pauseVideo 函式不同,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 屬性,不會影響 360 度影片播放的 yawpitchroll 屬性。詳情請參閱下方的 enableOrientationSensor 屬性。
傳遞至函式的 properties 物件包含下列屬性:
屬性
yaw 請參閱上方的定義
pitch 請參閱上方的定義
roll 請參閱上方的定義
fov 請參閱上方的定義
enableOrientationSensor 注意:這項屬性只會影響支援的裝置上的 360° 觀看體驗。這個布林值指出 IFrame 是否應回應信號在受支援裝置螢幕方向變更的事件 (例如行動瀏覽器的 DeviceOrientationEvent)。預設參數值為 true

支援的行動裝置
  • 如果值為 true,嵌入式播放器「只」會根據裝置的移動調整 yawpitchroll 屬性,才能播放 360 度影片。不過,您仍然可以透過 API 變更 fov 屬性,而 API 實際上是在行動裝置上變更 fov 屬性的唯一方法。此為預設行為。
  • 如果值為 false,則裝置的動作不會影響 360° 觀看體驗,且 yawpitchrollfov 屬性都必須透過 API 設定。

不支援的行動裝置
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

這個函式會指出影片播放器是否應持續播放播放清單,還是應該在播放清單中的最後一部影片結束後停止播放。預設行為是播放清單不會循環播放。

即使載入或繪製其他播放清單,這項設定仍會保持不變,這表示如果載入播放清單,使用 true 的值呼叫 setLoop 函式,然後載入第二個播放清單,第二個播放清單也會循環播放。

必要的 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 目前排序。根據預設,這個函式會按照播放清單擁有者指定的順序傳回影片 ID。不過,如果您呼叫 setShuffle 函式來隨機決定播放清單順序,則 getPlaylist() 函式的傳回值會反映重組順序。
player.getPlaylistIndex():Number
這個函式會傳回目前正在播放的播放清單影片索引。
  • 如果您尚未隨機播放播放清單,傳回的值會指示播放清單創作者將影片播放位置。傳回值會採用從零開始的索引,因此 0 的值能識別播放清單中的第一部影片。

  • 如果隨機播放播放清單,傳回值就會識別影片在隨機播放的播放清單中的順序。

新增或移除事件監聽器

player.addEventListener(event:String, listener:String):Void
為指定的 event 新增事件監聽器函式。「Events」(事件) 一節會列出玩家可能觸發的各種事件。事件監聽器是一個字串,會指定指定事件觸發時要執行的函式。
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 會指定與事件相關的值。請注意,onReadyonAutoplayBlocked 事件不會指定 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 支援的選項:

Module 選項 說明
captions fontSize 這個選項會調整播放器顯示字幕的字型大小。

有效值為 -10123。預設大小為 0,最小大小為 -1。將此選項設為 -1 以下的整數,可顯示最小的字幕大小;如果將這個選項設為 3 以上的整數,則會顯示最大的字幕大小。
captions 重新載入 這個選項會重新載入正在播放影片的隱藏式輔助字幕資料。如果擷取該選項的值,該值將是 null。將值設為 true,即可重新載入隱藏式輔助字幕的資料。
onAutoplayBlocked
每次瀏覽器封鎖自動播放功能或利用指令碼播放影片的功能時,就會觸發這個事件,統稱為「自動播放」。這包含透過下列任一播放器 API 嘗試播放的情況:

如果達到特定條件,大多數瀏覽器的政策會封鎖電腦、行動裝置和其他環境中的自動播放功能。可能觸發這項政策的執行個體包括:無需使用者進行互動即可將靜音播放,或權限政策尚未設定允許在跨來源 iframe 上自動播放的情況。

詳情請參閱瀏覽器專用政策 (Apple Safari / WebkitGoogle ChromeMozilla Firefox) 和 Mozilla 自動播放指南

範例

正在建立 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>

修訂版本記錄

November 20, 2023

The new onAutoplayBlocked event API is now available. This event notifies your application if the browser blocks autoplay or scripted playback. Verification of autoplay success or failure is an established paradigm for HTMLMediaElements, and the onAutoplayBlocked event now provides similar functionality for the IFrame Player API.

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.