YouTube iframe API с вкладками javascript - PullRequest
0 голосов
/ 24 апреля 2020

Я создаю онлайн-ТВ, который будет использовать прямые трансляции YouTube для нескольких каналов.

Каналы содержатся на вкладках. Видео необходимо остановить при смене вкладок, иначе вы можете услышать звук на заднем плане.

Вот ссылка на JSFiddle: https://jsfiddle.net/matlow/08k4csuh/

Мне удалось отключить «Канал 1» при переходе на другой канал с помощью:

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

и

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

Во вкладке javascript для l oop, которая также обрабатывает tabcontent[i].style.display = "none";

Я думаю, мне нужно использовать для l oop для вызова каждого экземпляра iframe ... но я новичок в javascript, поэтому я не совсем уверен, как этого добиться.

Также поможет использование iframe.postMessage('{"event":"command","func":"playVideo","args":""}', '*');, поэтому при повторном нажатии на соответствующую вкладку видео автоматически воспроизводится автоматически ... но, опять же, я не совсем уверен, как это реализовать.

Я работаю над этим в течение нескольких дней, поэтому, если у кого-то есть какие-либо советы или указатели, я был бы очень признателен!

Спасибо за чтение! :)

1 Ответ

0 голосов
/ 25 апреля 2020

Вы неправильно используете API YouTube. См. https://developers.google.com/youtube/iframe_api_reference

Программировать в вашей скрипке невозможно c play, поскольку вы не можете знать, когда проигрыватель YouTube готов, поскольку вы не тот инициализирую это. Ваши попытки play видео могут произойти слишком рано.

Programmati c pause (вам удалось приостановить первое видео) возможно благодаря enablejsapi=1 в iframe sr c и тот факт, что игрок готов к этому моменту.

Вот вилка вашей скрипки - https://jsfiddle.net/raven0us/ancr2fgz

Я добавил пару комментариев. Проверьте это.

// 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();
}

Впервые я работал с API iframe YouTube, но это кажется разумным.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...