0
votes

I am trying to make a webpage that uses the YouTube iframe API to display multiple videos which start playing automatically on load. I want 3 of the 4 videos to start playing in mute, but the 4th video to be playing with the audio. Finally, I am trying to create a mute/un-mute and pause/start button that allows me control all 4 videos simultaneously.

I have been playing around with the code for the audio feature and not sure why it isn't working. Right now 3 of the 4 videos use the api so I can control them all at once, and the last video is its own iframe which autoplays.

Here's the code if anyone want to play around with it:

HTML:

<div class="no-sound">
    <div data-id="EI0ib1NErqg"></div>
</div>
<div class="no-sound">
    <div data-id="fV6O722O_ew"></div>
</div>
<div class="no-sound">
    <div data-id="cKxRvEZd3Mw"></div>
</div>

<div id="sound">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/g95_9Qd7o9Y?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
</div>

JavaScript:

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var players;
function onYouTubePlayerAPIReady() {
    var players = document.querySelectorAll('.no-sound div')
    for (var i = 0; i < players.length; i++) {
        new YT.Player(players[i], {
            playerVars: {
                'autoplay': 1,
                'modestbranding': 1,
                'controls': 1,
                    events: {
                'onReady': onPlayerReady
                    }
            },
            videoId: players[i].dataset.id
        });
    }

}

      function onPlayerReady(event) {
        event.target.mute();
      }

Thank you in advance.

1

1 Answers

2
votes

Kindly change your code:

From:

new YT.Player(players[i], {
    playerVars: {
        'autoplay': 1,
        'modestbranding': 1,
        'controls': 1,
        events: {
        'onReady': onPlayerReady
        }
    },
    videoId: players[i].dataset.id
});

To

new YT.Player(players[i], {
    playerVars: {
        'autoplay': 1,
        'modestbranding': 1,
        'controls': 1},
        events: {
        'onReady': onPlayerReady
    },
    videoId: players[i].dataset.id
});

Base on the sample code given by google. Events element is outside the playerVars element. Here is the link for the supported list of parameters int playerVars element.

function onYouTubeIframeAPIReady() {
    var player;
    player = new YT.Player('player', {
        videoId: 'M7lc1UVf-VE',
        playerVars: { 'autoplay': 1, 'controls': 0 },
        events: {
            'onReady': onPlayerReady,
            'onPlaybackQualityChange': onPlayerPlaybackQualityChange,
            'onStateChange': onPlayerStateChange,
            'onError': onPlayerError
        }
    });
}

See this jsfiddle as example.