【问题标题】:Youtube iframe API with javascript tabs带有 javascript 标签的 Youtube iframe API
【发布时间】:2020-04-24 19:35:26
【问题描述】:

我正在构建一个在线“电视”,它将为多个频道使用 YouTube 直播。

频道包含在选项卡中。更改选项卡时需要停止视频,否则您可以在后台听到音频。

这里是 JSFiddle 的链接:https://jsfiddle.net/matlow/08k4csuh/

在切换到另一个频道时,我已经设法关闭了“频道 1”:

  var iframe = document.getElementsByClassName("tvscreen")[0].contentWindow;

 iframe.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');

在标签 javascript for 循环中也处理 tabcontent[i].style.display = "none";

我认为我需要使用 for 循环来调用 iframe 的每个实例......但我对 javascript 很陌生,所以我不太确定如何实现这一点。

使用iframe.postMessage('{"event":"command","func":"playVideo","args":""}', '*'); 也将有所帮助,因此在单击相关选项卡时视频会再次自动播放......但我不太确定如何实现这一点。

我已经为此工作了几天,如果有人有任何提示或指示,我将不胜感激!

感谢阅读! :)

【问题讨论】:

    标签: javascript api iframe youtube


    【解决方案1】:

    您没有正确使用 YouTube 的 API。见https://developers.google.com/youtube/iframe_api_reference

    在您的小提琴中,程序化play 是不可能的,因为您不知道 YouTube 播放器何时准备就绪,因为您不是初始化它的人。您尝试play 视频可能为时过早。

    由于 iframe src 中的 enablejsapi=1 以及播放器此时已准备就绪这一事实,因此可以进行程序化 pause(您设法暂停了第一个视频)。

    这是你小提琴的一个分支 - https://jsfiddle.net/raven0us/ancr2fgz

    我添加了几个 cmets。看看这些。

    // load YouTube iframe API as soon as possible, taken from their docs
    var tag = document.createElement('script');
    tag.id = 'iframe-demo';
    tag.src = 'https://www.youtube.com/iframe_api';
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
    // initialised players are kept here so we don't have to destroy and reinit
    var ytPlayers = {};
    
    function mountChannel(channel) {
        var player;
        var iframeContainer = document.querySelectorAll('#' + channel + ' iframe');
    
        // if the channel & iframe we want to "mount" exist, check for playing iframes before doing anything else
        if (iframeContainer.length > 0) {
            // Object.keys() is ECMA 5+, sorry about this, but no easy to check if an object is empty
            // alternatively, you could have an array, but in that case, you won't be able to fetch a specific player as fast
            // if you don't need that functionality, array is as good cause you will just loop through active players and destroy them
            var activePlayersKeys = Object.keys(ytPlayers);
            if (activePlayersKeys.length > 0) { // if players exist in the pool, destroy them
                for (var i = 0; i < activePlayersKeys.length; i++) {
                    var activeChannel = activePlayersKeys[i];
                    var activePlayer = ytPlayers[activeChannel];
    
                    activePlayer.getIframe().classList.remove('playing'); // mark pause accordingly, by removing class, not necessary
                    activePlayer.pauseVideo();
                }
            }
    
            // check if player already initialised and if player exists, check if it has resumeVideo as a function
            if (ytPlayers.hasOwnProperty(channel)) {
                ytPlayers[channel].playVideo();
            } else {
                var iframe = iframeContainer[0];
                player = new YT.Player(iframe, {
                    events: {
                        'onReady': function (event) {
                            // event.target is the YT player
                            // get the actual DOM node iframe nad mark it as playing via a class, styling purposes, not necessary
                            event.target.getIframe().classList.add('playing');
                            // play the video
                            event.target.playVideo();
                            // video may not autoplay all the time in Chrome, despite its state being cued and this event getting triggered, this happens due to a lot of factors 
    
                        },
                        // you should also implement `onStateChange` in order to track video state (as a result of user actions directly via YouTube controls) - https://developers.google.com/youtube/iframe_api_reference#Events
                    }
                });
    
                // append to the list
                ytPlayers[channel] = player;
            }
        }
    }
    
        // Get the element with id="defaultOpen" and click on it
    function onYouTubeIframeAPIReady() {
        // YouTube API will call this when it's ready, only then attempt to "mount" the initial channel
        document.getElementById("defaultOpen").click();
    }
    

    这是我第一次使用 YouTube 的 iframe API,但这似乎是合理的。

    【讨论】:

      猜你喜欢
      • 2012-08-25
      • 1970-01-01
      • 2014-03-29
      • 2012-02-15
      • 2019-04-10
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      • 2012-11-18
      相关资源
      最近更新 更多