2015-03-02 29 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

相关问题