当我浏览获取并应用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);
答案 0 :(得分:3)
onYouTubeIframeAPIReady
函数必须位于全局范围内,因此必须在window
对象上定义。
因此,在使用browserify的情况下,您需要在global
对象上定义它:
global.onYouTubeIframeAPIReady = function() {
player = new YT.Player('player', {
videoId: 'M7lc1UVf-VE',
playerVars: {
'controls': 1,
'rel': 1,
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}