我已经尝试了一段时间,以创建一个嵌入式YouTube播放器,当有人加载页面时,该播放器会自动以随机播放方式启动播放列表。几次搜索使我找到了另一种解决方案:当当前视频结束时,在播放列表中加载随机索引的新视频。
这是我目前拥有的代码:
<div id="player"></div>
<button value="next" onclick="next();">Next</button>
<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,
'onStateChange': onPlayerStateChange
}
});
}
var oldNumber = 0;
var NewNumber = 0;
function newRandomNumber(min, max) {
oldNumber = NewNumber;
NewNumber = Math.floor(Math.random() * max) + min;
if (NewNumber == oldNumber) {
newRandomNumber(min, max);
} else {
return NewNumber;
}
}
function onPlayerReady(event) {
next();
}
function next() {
player.loadPlaylist({
'listType': 'playlist',
'list': 'PLxBKLJmrCEphpgRihb-H0QUColR_bFu6s',
'index': newRandomNumber(0, 139),
'startSeconds': '0',
'suggestedQuality': 'small'
});
player.setShuffle({
'shufflePlaylist': true
});
}
function onPlayerStateChange(event) {
if (event.data == 0) {
next();
}
}
</script>
经过一些反复的测试,看起来这部分无法正常工作:
function onPlayerStateChange(event) {
if (event.data == 0) {
我尝试将其设置为其他整数并进行适当的测试,但似乎没有东西会触发该事件。
值得一提的是,大部分代码都是从这里获取的,但我无法在该页面上找到任何帮助:Shuffle Playlist fix for Youtube API
谢谢。
最佳答案
如果我们在实例化YouTube播放器时设置了random和playlist参数,则随机播放和事件有效。这是显示工作球员的代码:
<div id="player"></div>
<button value="next" onclick="next();">Next</button>
<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,
'onStateChange': onPlayerStateChange
},
playerVars: {
'html5': 1,
'listType': 'playlist',
'list': 'PLxBKLJmrCEphpgRihb-H0QUColR_bFu6s',
'index': newRandomNumber(0, 139),
'startSeconds': '0',
'autoplay': 1,
'suggestedQuality': 'small'
}
});
}
var oldNumber = 0;
var NewNumber = 0;
function newRandomNumber(min, max) {
oldNumber = NewNumber;
NewNumber = Math.floor(Math.random() * max) + min;
if (NewNumber == oldNumber) {
newRandomNumber(min, max);
} else {
console.log(NewNumber);
return NewNumber;
}
}
function onPlayerReady(){
//nothing to do as of now.
}
function next() {
console.log('next called');
player.setShuffle({
'shufflePlaylist': true
});
}
function onPlayerStateChange(event) {
if (event.data == 0) {
next();
}
}
</script>
关于javascript - onStateChange将不会触发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33978525/