2012-11-01 85 views
20

我想使用YT.Player代碼,以便我可以檢測事件。我有一個帶有Youtube視頻ID的CSV文件和一個將ID放在數組中並希望能夠在用戶單擊圖像時動態更改ID的功能。從本質上講是這樣的:如何動態更改Youtube Player視頻ID

HTML

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

的JavaScript

// 2. This code loads the IFrame Player API code asynchronously. 
var tag = document.createElement('script'); 
tag.src = "//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. 
// NOTE: videoId is taken out and instead is placed as the generated IFRAME src from the postSelection function 

var player; 
function onYouTubeIframeAPIReady() { 
    player = new YT.Player('player', { 
     height: '100%', 
     width: '100%', 
     videoId: '<<CALL TO FUNCTION OR VARIABLE HERE>>', 
     events: { 
     //'onReady': onPlayerReady, 
     'onStateChange': onPlayerStateChange 
     } 
    }); 
} 

如果你熟悉這個代碼,那麼會發生什麼是#player DIV通過一個IFRAME取代。我可以使用此功能更改IFRAME源:

function postSelection() { 
    $("#player").attr("src", _selected.attributes.url); //_selected.attributes.url comes from the CVS file 
} 

但是,這是非常麻煩的,不能跨瀏覽器友好。如果我使用標準的IFRAME而不是YT Player API,那麼一切正常。但我想檢測結束,並暫停等,所以我必須使用API​​。我的猜測是,這是一個與狀態有關的問題,持久性在創建IFRAME的時候會丟失。

問候。

+1

你甚至讀過[youtube api文檔](https://developers.google.com/youtube/iframe_api_reference)嗎?您可以使用您在onYouTubeIframeAPIReady中獲得的player變量來進行api調用。 – Philipp

回答