【问题标题】:How do I start and stop youtube videos created with the youtube iframe API?如何启动和停止使用 youtube iframe API 创建的 youtube 视频?
【发布时间】:2018-05-29 06:55:52
【问题描述】:

我创建了一个环绕 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】:

    这是我的解决方案 -> 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>
    

    【讨论】:

    • 如果是这样,您可以将问题标记为已回答。
    猜你喜欢
    • 2012-05-08
    • 1970-01-01
    • 2011-10-04
    • 2021-01-01
    • 2012-07-24
    • 2017-07-18
    • 2012-07-02
    • 2014-03-14
    • 2012-11-05
    相关资源
    最近更新 更多