Youtube Javascript播放器ASPI“ytplayer不是函数”

问题描述 投票:2回答:2

我在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();

我得到了not function错误:

TypeError:ytplayer.playVideo不是函数

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

有谁能够帮我?

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

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

javascript youtube-javascript-api
2个回答
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
投票

如果你遵循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

© www.soinside.com 2019 - 2024. All rights reserved.