问题
I have been trying to set-up my youtube api to shuffle my playlist but the order is the same all the time...
Here is the link where I am getting my code from https://developers.google.com/youtube/iframe_api_reference#setShuffle
Am I calling it right?
here is my code below
<div id="player"></div>
<script>
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 player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
player.loadPlaylist({'listType': 'playlist', 'list': 'PLF776D41D8211F340','index': '0','startSeconds': '0','suggestedQuality': 'hd720'});
player.setShuffle({'shufflePlaylist' : 1});
}
</script>
I have tried setting shufflePlaylist to 'true', I have tried cueplaylist instead of loadplaylist and I have even tried putting the shufflePlaylist in the load Playlist...nothing is getting shuffled.
I have looked into this and I see that it was an issue with the API, but that was 2 years ago, is there a solution to this issue?
Below is what I have tried and didn't work
player.setShuffle(1);
player.setShuffle('1');
player.setShuffle(true);
player.setShuffle('true');
player.setShuffle({'shufflePlaylist' : true});
player.setShuffle({'shufflePlaylist' : 1});
player.setShuffle({'shufflePlaylist' : 'true'});
player.setShuffle({'shufflePlaylist' : '1'});
I have also tried copying and example from here....https://developers.google.com/youtube/youtube_player_demo
The Shuffle works here after u load the playlist and click a button.
回答1:
This is a known bug that is yet to be fixed - see this post
A work around however is to pass a random number to playVideoAt
, as follows:
var getRandom = function(min, max) {
return Math.random() * (max - min) + min;
};
var playRandomTrack = function() {
num = getRandom(0, 99);
player.playVideoAt(num);
};
回答2:
I found the solution. You have to load the player.setShuffle(true)
just after the first video starts:
function onPlayerReady(event) {
event.target.playVideo();
setTimeout(setShuffleFunction, 1000);
}
function setShuffleFunction(){
player.setShuffle(true);
}
Demo on my online music tv website
回答3:
More or less the same solution as Ivan's. Works for me!
function onPlayerReady(event) {
event.target.mute();
setTimeout( function() {
event.target.setShuffle(true);
event.target.setLoop(true);
}, 2000);
}
If you launch it directly, it will definitely not work (I have noticed, to my frustration).
回答4:
Try the following:
function onPlayerStateChange(event) {
if(event.data === 0) {
player.setShuffle(true);
player.playVideo();
}
}
来源:https://stackoverflow.com/questions/15866979/youtube-api-playlist-shuffle-not-working