如何获取现有YouTube播放器的参考? [英] How do I get the reference to an existing YouTube player?
问题描述
< iframe的宽度= 560 HEIGHT = 315 SRC = // www.youtube.com/embed/M7lc1UVf-VE FRAMEBORDER = 0 的allowFullScreen>< / iframe中> ;
关于使用上述源代码嵌入YouTube视频时会发生什么问题,我有几个问题。该代码应生成一个YouTube播放器对象,以用户喜欢的方式处理视频。当我自己使用Youtube播放器API(而不是使用嵌入代码)生成Youtube播放器时,我可以在其上调用调用函数。
I have a few questions on what happens when I embed a YouTube video using source code like above. The code should generate a YouTube Player object that processes the video the way users like. When I generate a Youtube Player by myself using Youtube Player API(instead of using the embed code), I can call call functions on it.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
//player.playVideo(); will play the video.
我的问题是,如何控制嵌入代码生成的播放器对象?换句话说,请从页面 http://www.youtube.com/watch? v = M7lc1UVf-VE ,如何通过调用 SOMEPlayer.playVideo()
来播放视频?当你转到网址时, ytplayer
对象可用,但它似乎不包含必要的功能。
My question is, how do I control the player object generated by the embed code? To put it in another way, from page http://www.youtube.com/watch?v=M7lc1UVf-VE, how do I play the video by calling SOMEPlayer.playVideo()
? When you go to the url, ytplayer
object is available, but it doesn't seem to contain the necessary functions.
此问题可能与此一>。
推荐答案
这可以像下面这样完成。
This can be done like the following.
给定一个一般YouTube嵌入源代码:
Given a general YouTube embed source code:
< iframe width =560height =315src =// www.youtube.com / embed / M7lc1UVf-VEframeborder =0allowfullscreen>< / iframe>
a。添加 enablejsapi
参数并将其设置为true
a. Add a enablejsapi
parameter and set it true
index.html
< iframe width =560height =315src =// www.youtube.com/embed/M7lc1UVf-VEframeborder = 0enablejsapi =1allowfullscreen>< / iframe>
b。给它一个唯一的ID
b. Give it a unique id
< iframe id =youtube-videowidth =560height =315src =/ /www.youtube.com/embed/M7lc1UVf-VE FRAMEBORDER = 0 enablejsapi = 1 的allowFullScreen>< / iframe中>
℃。加载iFrame API并创建一个引用现有iFrame的播放器
c. Load iFrame API and create a player that references the existing iFrame
application.js
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('youtube-video', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady() {
console.log("hey Im ready");
//do whatever you want here. Like, player.playVideo();
}
function onPlayerStateChange() {
console.log("my state changed");
}
这篇关于如何获取现有YouTube播放器的参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!