Youtube Javascript播放器ASPI" ytplayer不是一个功能"

时间:2014-10-30 15:17:57

标签: javascript youtube-javascript-api

我在html中有这段代码:

        <div class="flex-video widescreen youtube">
            <iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube.com/embed/{{Video.v_id}}?autoplay=1&enablejsapi=1&autohide=1" frameborder="0" allowfullscreen> </iframe>
        </div>

和Javascript中的代码:

        function onYouTubePlayerReady(playerId) {
            console.log("player ready");
            ytplayer = document.getElementById("ytplayer");
        }

当我输入Firefox控制台时:

ytplayer.playVideo();

我得到了无功能错误:

  

TypeError:ytplayer.playVideo不是函数

console.log("player ready");根本不打印。

有人能帮助我吗?

我想用javascript api控制播放器而不是IFrame api。 我希望视频播放器在html5中。

编辑: 我启用了jspapi(enablejsapi = 1)

2 个答案:

答案 0 :(得分:6)

对我来说有用的是按文件和JS添加youtube,然后使用onYoutubePlayerAPIReady事件,如下所示:

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

答案 1 :(得分:1)

如果您遵循YouTube API Player

的文档

<强> HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="player"></div>
</body>
</html>

<强> JS

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: 'l-gQLqv9f4o',
        events: {
            'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
        }
    });
}

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
    event.target.playVideo();
}

function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING) {

    }
}

function stopVideo() {
    player.stopVideo();
}

<强> Live demo