如何启动和停止使用youtube iframe API创建的YouTube视频?

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

我创建了一个包裹YT.Player的函数。它将youtube视频注入文档:

function swGetYoutubeVids ( elById, videoId ) {
            var playerName = elById ;
            window.playerName = new YT.Player( elById, {
                height : '',
                width: '',
                videoId : videoId,
                playerVars: {
            enablejsapi : 1,
            modestbranding : 1,
            origin : playerOrigin,
            showinfo : 0
        },

 }) ;

它的工作原理:如果我做swGetYoutubeVids('player_1', 'vha-Swtnj-U'),就会创建一个新的视频

该函数还在窗口上创建变量,因此我可以控制播放器。好吧,至少这是个主意。

在上面的调用中,将创建window.player_1。我可以通过从浏览器控制台测试window.player_1的存在来确认这一点。

但是,window.player_1.playVideo()不起作用。根据API文档,该调用应该开始播放视频。相反,我得到'playVideo不是一个功能'。

那么我该如何实际播放视频呢?

javascript youtube-api
1个回答
0
投票

这是我的解决方案 - > https://plnkr.co/edit/Tb0YpAtsiruK7H63wabj?p=preview

加载脚本是异步的。初始化播放器后,您需要链接事件。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <script src="https://www.youtube.com/iframe_api"></script>

</head>

<body>
<div id="player_1"></div>

<div class="wrap" style="display: none">
    <button id="play" onclick="playVideo()">play</button>
    <button id="pause" onclick="pauseVideo()">pause</button>
</div>

<script>
    var player;

    function onYouTubeIframeAPIReady(){
        swGetYoutubeVids('player_1', 'vha-Swtnj-U');
    }

    function swGetYoutubeVids(elById, videoId ) {
        player = new YT.Player(elById, {
            height: '390',
            width: '640',
            videoId: videoId,
            events: {
                'onReady': onPlayerReady
            },
            playerVars: {
                enablejsapi : 1,
                modestbranding : 1,
                //origin : playerOrigin,
                showinfo : 0
            },
        });
    }

    function onPlayerReady(){
        // here is player ready
        console.info(player);
        document.getElementsByClassName('wrap')[0].style.display = 'block';
    }

    function playVideo() {
        player.playVideo()
    }

    function pauseVideo() {
        player.pauseVideo()
    }
</script>
</body>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.