2015-03-02 103 views
2

以下是我的代碼:我試圖在運行時獲取當前的YouTube時間。但是,它總是提醒我錯誤消息:「Uncaught TypeError:undefined不是函數」。它使我困惑不已。因爲我已經提前定義了球員。爲什麼該功能無法使用?除了getCurrentTime方法之外,我還測試其他方法,如getVolume(),它也會遇到同樣的錯誤。Youtube API不起作用 - 未捕獲TypeError:undefined不是函數

任何幫助?提前致謝!在畫面

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>THis is YOutube API testing </title> 
</head> 

<body> 

    <div class="container"> 
    <iframe id="video" width="560" height="315" src="https://www.youtube.com/embed/02GcUZ6hgzo" frameborder="0" allowfullscreen></iframe> 
    </div> 

    <script> 
    //import YouTube API script 
    var tag = document.createElement('script'); 
    tag.src = "https://www.youtube.com/iframe_api"; 
    var firstScriptTag = document.getElementsByTagName('script')[0]; 
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

    //create the YouTube Player 
    var player; 

    function onYouTubeIframeAPIReady() { 
    console.log("API is Ready"); 
    player = new YT.Player("video", { 
    events : { 
     'onReady': onPlayerReady(), 
     'onStateChange': onStateChangeEvent() 
     } 
    }); 
    } 
    function onPlayerReady() { 
    console.log("My plaer is onReady"); 

    } 
    function onStateChangeEvent(){ 
    setInterval(function(){ 
     var time = player.getCurrentTime(); 
     //var volume = player.getVolume(); 
     console.log("Get Current Time: " + time); 
    },1000); 

    } 
    </script> 
</body> 
</html> 

錯誤消息: enter image description here

回答

4

我只是想通了。這是因爲我沒有在我的網址中啓用JavaScript。

這裏是Google Official Docs.

Enabling the JavaScript API for a chromeless player 

If your application is using a chromeless player, use the following URL to load the player in your application and enable JavaScript API handlers in the player. You can then build your own custom player controls using JavaScript: 

http://www.youtube.com/apiplayer?enablejsapi=1&version=3 
Enabling the JavaScript API for an embedded player 

Use the following URL to load an embedded video player. In the URL, replace the string VIDEO_ID with the 11-character YouTube video ID that identifies the video that the player will show. 

http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1 
+0

聽到這很棒。繼續並將此作爲答案,以便其他人可以看到解決方案是什麼 – pertrai1 2015-03-03 18:14:11

+1

這對其他人來說非常有用。其新的iframe API(https://developers.google.com/youtube/iframe_api_reference)的Youtube文檔沒有明確說明包含enablejsapi = 1參數。只有棄用的API文檔纔會這麼說!如果你像我一樣,而且你正在使用新的iframe API,並且你也手動將iframe放入你的html中,而不是像他們建議的那樣通過API生成它,那麼你需要包含這個參數! – 2015-04-15 20:54:00

0

我不知道是怎麼回事。當我把它放在JSFiddle時,它似乎在工作。你能否解釋一下我可能缺少的東西:

Don't know why I have to add code if I don't see any problems with the code in question? 
+0

我剛去到您創建的jsfiddle的描述,但我沒有看到它顯示在控制檯上任何東西。通常,它應該調用已準備好的事件,對吧? – 2015-03-02 16:51:16

相關問題