当我浏览获取并应用Youtube iFrame API的脚本时,onYoutubeIframeAPIReady()
不会运行,请求的视频也不会加载。有办法绕过这个吗?我做错什么了吗?
这是我的脚本:
var Command = require('../model/command.js');
var Control = require('../model/control.js');
var User = require('../model/user.js');
var socket = io();
var executions = {};
executions[1] = function() { player.playVideo(); };
executions[2] = function() { player.pauseVideo(); };
var control = Control();
var now = function() { return new Date().getTime() / 1000; };
var user = User();
var update = function() {
control.room = $('#name').text();
if (user.last) {
if (user.command.date > user.last) {
player.seekTo(user.command.time, true);
executions[user.command.state]();
control.last = user.command.date;
}
} else {
player.seekTo(user.time, true);
executions[user.state]();
control.last = now();
}
control.time = player.getCurrentTime();
control.state = player.getPlayerState();
socket.emit('control', control);
};
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId: 'M7lc1UVf-VE',
playerVars: {
'controls': 1,
'rel': 1,
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
$('#youtube-controls').show();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.Playing) {}
}
$('#youtube-controls').hide();
// Control
$('#pause').click(function() {
player.pauseVideo();
control.command = Command(2, player.getCurrentTime());
});
$('#play').click(function() {
player.playVideo();
control.command = Command(1, player.getCurrentTime());
});
// Input
socket.on('update', function(message) { user = message; });
// Output
setInterval(update, 1000);
onYouTubeIframeAPIReady
函数必须位于全局作用域中,因此必须在window
对象上定义它。
因此,在使用browserfy的情况下,您需要在global
对象上定义它:
global.onYouTubeIframeAPIReady = function() {
player = new YT.Player('player', {
videoId: 'M7lc1UVf-VE',
playerVars: {
'controls': 1,
'rel': 1,
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}