对于我工作的学院,我正试图在网页的横幅上自动播放一段youtube视频。API每次加载都不正确。我不确定我能做些什么来解决这个问题。
我试过:
-
只有当DOM准备好时,才将添加youtube API脚本移动到。
-
将代码放置在页面的顶部和底部。
-
检查播放器对象是否创建正确,如果没有,尝试重新创建它,我了解到这打破了API。
如果我去掉页面上的所有内容,只加上横幅,视频加载频率会更高,但仍然不是100%。
在这里,我在通过YouTube API加载视频的页面上提供了脚本。
更新:通过登录控制台,我可以看出播放器对象没有完全初始化。当它没有正确创建时,这就是对象打印出来的样子:
Y {b: null, a: null, h: null, closure_uid_165988549: 1, g: 1, …}
这里是正确的时候:
Y {b: Wa, a: iframe#ytplayer, h: div#ytplayer, closure_uid_16195269: 1, g: 1, …}
我错了,找不到视频ID。每次调用函数之前都会设置视频,所以这不应该是一个问题。
<div id="ytplayer"></div>
<script>
defer(function() {if(window.mobile === true) { $('#ytplayer').remove(); }});
var ready;
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
// var videoId = 'ZCESafUzSRo';
function onYouTubeIframeAPIReady() {
checkFunction();
}
function checkFunction() {
console.log("checkFunction called");
setYTready(ready);
}
function setYTready(ready) {
console.log("setYT ready called");
ready = true;
mtuPlayerCreate(player);
}
function mtuPlayerCreate(player) {
console.log("mtu create called");
if((player == undefined) && ( document.getElementById("play-yt") != null)) {
console.log("Creating player");
player = new YT.Player('ytplayer', {
height: '52.65%',
width: '100%',
playerVars: {
'controls': 0,
'showinfo': 0,
'rel': 0,
'iv_load_policy': 3
},
videoId: videoId,
events: {
'onReady': onPlayerReady,
// Removing the following if loop shouldn't be enabled
onStateChange:
function(e){
if (e.data === YT.PlayerState.ENDED) {
player.playVideo();
}
}
}
});
}
console.log("player redo below");
console.log(player);
if(player.A == false) {
//setTimeout(function() {location.reload();}, 2000);
} else {
return;
}
}
function onPlayerReady(event) { /* configuring default playing and mute settings */
console.log("on ready has been called")
var autoPlay = 1;
var autoMute = 1;
if(autoPlay === 1) { event.target.playVideo(); }
if(document.getElementById('play-yt') && autoPlay === 1) { document.getElementById('play-yt').className = 'pause'; }else if(document.getElementById('play-yt')) { document.getElementById('play-yt').className = 'play'; }
if(autoMute === 1) { event.target.mute(); }
if(document.getElementById('mute-yt') && autoMute === 1) { document.getElementById('mute-yt').className = 'mute'; }else if(document.getElementById('mute-yt')) { document.getElementById('mute-yt').className = 'loud'; }
if(document.getElementById('yt-yt')) { document.getElementById('yt-yt').className = ''; }
}
window.onload = function() { /* this handles what happens when the player and its buttons are clicked on */
document.getElementsByClassName('media-black')[0].onclick=function(e) {
if(e.target.id !== 'yt-yt' && e.target.id !== 'mute-yt') {
if(player.getPlayerState() === -1 || player.getPlayerState() === 2 || player.getPlayerState() === 5) {
player.playVideo();
if(document.getElementById('play-yt')) { document.getElementById('play-yt').className = 'pause'; }
if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Played', window.location.href]);
}else{
player.pauseVideo();
if(document.getElementById('play-yt')) { document.getElementById('play-yt').className = 'play'; }
if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Paused', window.location.href]);
}
}
else if(e.target.id === 'yt-yt' && e.target.id !== 'mute-yt') {
window.open('http://www.youtube.com/watch?v=' + videoId, '_blank');
player.pauseVideo();
if(document.getElementById('play-yt') && document.getElementById('play-yt').className === 'pause') { document.getElementById('play-yt').className = 'play'; }
if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Went to YouTube', window.location.href]);
}else{
if(player.isMuted() || player.getVolume() === 0) { player.unMute(); player.setVolume(100); document.getElementById('mute-yt').className = 'loud'; }else{ player.mute(); document.getElementById('mute-yt').className = 'mute'; }
if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Sound Adjusted', window.location.href]);
}
};
}
//
//This could be improved, test if it's mobile and load if not instead of loading and then removing if mobile
//
// Load the IFrame Player API code asynchronously.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("dom ready!");
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
});
</script>
</div>
它需要做的是:
- 加载API
- 加载具有给定视频ID的播放器对象
- 将iframe添加到正确的位置
- 自动播放视频
每次加载页面时都需要执行此操作。
我不知道你为什么用这种方式加载YouTube iframe播放器,但是,我通过修改你的代码制作了这个jsfiddle,我让YouTube播放器iframe正常工作。
这些是我所做的修改-你可以在修改后的代码中找到更多的评论:
- 我评论了
mtuPlayerCreate
-你想添加另一个YouTube Iframe吗 - 添加
onPlayerStateChange
功能,用于设置HTML元素的功能-能够控制iframe-"播放/暂停,(取消)静音视频"> controls
的值为0,我将其设置为1
,以检查它是否通过单击HTML元素正确控制了YouTube iframe
这是jsfiddle代码:
// No need for replace the elemnt - YouTube Iframe Player will load in this object and HTML element:
var player;
// This is your videoId "you had it commented".
// it was the video is not available:
//var videoId = 'ZCESafUzSRo';
// Video: "Microsoft Windows Mixed Reality update | October 2018" - by Microsoft Hololens.
var videoId = '00vnln25HBg';
// Check whether iframe is mute.
var isUnMuted = false;
// Here, the YouTube Player API will build the iframe in the "ytplayer" HTML element
// and in the "player" variable.
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
height: '52.65%',
width: '100%',
playerVars: {
'controls': 1,
'showinfo': 1,
'rel': 0,
'iv_load_policy': 3,
'autoplay': 1,
'loop': 1,
},
videoId: videoId,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
// After loading the iframe, set the "playVideo" onclick event on "playButton" anchor element.
document.getElementById('play-yt').onclick = function() {
player.playVideo();
};
// Thanks to this answer, here you can check the status of "mute" - I culdn't make it work, in the "onPlayerStateChange" function though.
// Source: https://stackoverflow.com/a/36436765/4092887
document.getElementById('mute-yt').innerHTML = 'MUTE';
document.getElementById('mute-yt').onclick = function() {
player.mute();
};
document.getElementById('yt-yt').innerHTML = 'UNMUTE';
document.getElementById('yt-yt').onclick = function() {
player.unMute();
};
}
function checkFunction() {
console.log("checkFunction called");
setYTready(ready);
}
function setYTready(ready) {
console.log("setYT ready called");
// Not sure what you're doing here = do you want load another youtube iframe?
//mtuPlayerCreate(player);
}
function mtuPlayerCreate(player) {
console.log("mtu create called");
if ((player == undefined) && (document.getElementById("play-yt") != null)) {
}
console.log("player redo below");
console.log(player);
if (player.A == false) {
//setTimeout(function() {location.reload();}, 2000);
} else {
return;
}
}
/* configuring default playing and mute settings */
/* You only need set here the following line: */
function onPlayerReady(event) {
event.target.playVideo();
}
/* this handles what happens when the player and its buttons are clicked on */
/* You can do it in this way instead: */
function onPlayerStateChange(e) {
// Removing the following if loop shouldn't be enabled.
// This is for emulate "loop" functionality.
if (e.data === YT.PlayerState.ENDED) {
player.playVideo();
}
// If the video is PLAYING, set the onclick element for pause the video.
// Once the "playButton" is clicked, the video will be paused.
if (e.data == YT.PlayerState.PLAYING) {
document.getElementById('play-yt').innerHTML = 'PAUSE';
document.getElementById('play-yt').onclick = function() {
player.pauseVideo();
};
}
// If the video is PAUSED, set the onclick element for pause the video.
// Once the "playButton" is clicked, the video will resume the video = continue playing the video.
if (e.data == YT.PlayerState.PAUSED) {
document.getElementById('play-yt').innerHTML = 'PLAY';
document.getElementById('play-yt').onclick = function() {
player.playVideo();
};
}
}
//
//This could be improved, test if it's mobile and load if not instead of loading and then removing if mobile
//
// Load the IFrame Player API code asynchronously.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("dom ready!");
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="ytplayer"></div>
<p>
<div>
<span>Control your Youtube Iframe Player:</span>
</div>
<div id="play-yt">PLAY</div>
<div id="mute-yt">MUTE</div>
<div id="yt-yt">UNMUTE</div>
</p>