Reputation: 33
This is working just fine, however it seems to only auto play every now and then. When I try to load the website through incognito it doesn't auto play at all:
I'm wondering if it is even the code or it's just because YouTube is limiting something
(function(window, document, undefined) {
'use strict';
function removeElement(array, element) {
return array.filter(function(el) {
return el !== element
});
}
function changeVideo() {
if (player.getCurrentTime() >= delay) {
var currentVideo = player.getVideoData().video_id,
randomVideo = removeElement(videoPlaylist, currentVideo)[Math.floor(Math.random() * (videoPlaylist.length - 1))];
player.loadVideoById(randomVideo);
}
}
function onPlayerStateChange(event) {
clearInterval(repeat);
if (event.data === 1) {
repeat = setInterval(changeVideo, 500);
}
}
window.onYouTubeIframeAPIReady = function() {
var randomVideo = videoPlaylist[Math.floor(Math.random() * videoPlaylist.length)];
player = new YT.Player('player', {
height: '315',
width: '560',
videoId: randomVideo,
playerVars: {
'autoplay': 1,
'controls': 0,
'showinfo': 0,
'iv_load_policy': 3
},
events: {
'onStateChange': onPlayerStateChange
}
});
}
var tag = document.createElement('script'),
player,
videoPlaylist = ['wfF0zHeU3Zs', 'WNcsUNKlAKw', '9E6b3swbnWg'],
delay = 10, //s
repeat;
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
})(window, document);
Upvotes: 3
Views: 247
Reputation: 1116
Browsers are blocking auto play for when the sound is on. https://www.theverge.com/2018/5/3/17251104/google-chrome-66-autoplay-sound-videos-mute https://www.theverge.com/2019/3/19/18272377/firefox-66-release-date-news-features-autoplaying-videos
A way around this might be to mute the video until the user moves their mouse over the video. (I think this is a common solution but correct me if I'm wrong)
You also have to think about the fact that users might not want to have the video autoplaying depending on what kind of website this is implemented into.
The reason it sometimes seems to be working for you is because chrome is learning that you want audio on the website you're creating but for example for me it is never playing.
Upvotes: 5