我想创建一个YouTube视频播放器,每次访问网页时都会重新排列一系列视频,然后按顺序播放它们。
到目前为止,我的代码能够从阵列中选择一个随机视频播放它,然后随机选择另一个视频并播放它。
这个问题是视频重叠。当它随机化数组时,我希望它们全部按顺序播放:如3,2,1或2,1,3或3,1,2。没有重复。
此刻,它会播放3次任意数量的视频。
每次访问页面时,此函数都会对数组进行洗牌,此部分可以正常工作。
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
这是根据https://developers.google.com/youtube/iframe_api_reference
改编的代码 // 1. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 2. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
var list = ['rgAYRbeO9GI','6wKxfH9NpVE','OJ9qLosjjH8']
shuffle(list); // shuffles the array
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '585',
width: '960',
// videoId: list[Math.floor(Math.random() * list.length)],
videoId: list[0], // accesses the first index of the newly sorted list array, Ideally I want to play the next video
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 3. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 4. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED && !done) { // once the video is finished the onPlayerReady() function repeats.
onPlayerReady();
done = true;
}
}
我需要一种方法将list [0]索引移动到下一个,我不知道在哪里放置循环。有什么想法吗?
答案 0 :(得分:0)
我设法使用此代码将youtube播放列表随机化:
var playlistLength = 198;
function onPlayerReady(event) {
player.cuePlaylist({
'listType': 'playlist',
'list': 'PLCEwouDaI4SXpFtD8wVnPY7wfx7LpXXRw',
'index' : [Math.floor(Math.random() * playlistLength)]
});
setTimeout( function() {
//event.target.stopVideo();
//event.target.playVideoAt(3);
event.target.setShuffle(true);
event.target.playVideo();
event.target.setLoop(true);
},
1000);
}