如何获取对现有 YouTube 播放器的引用? [英] How do I get the reference to an existing YouTube player?

查看:31
本文介绍了如何获取对现有 YouTube 播放器的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<iframe width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen></iframe>

关于使用上述源代码嵌入 YouTube 视频时会发生什么,我有几个问题.该代码应生成一个 YouTube Player 对象,该对象以用户喜欢的方式处理视频.当我使用 Youtube Player API(而不是使用嵌入代码)自己生成一个 Youtube Player 时,我可以在其上调用调用函数.

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()播放视频?当你转到 url 时,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.

推荐答案

这可以像下面这样完成.

This can be done like the following.

给定一个通用的 YouTube 嵌入源代码:

Given a general YouTube embed source code:

<iframe width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen></iframe>

一个.添加 enablejsapi 查询参数并在 src URL 中设置为 1

a. Add a enablejsapi query param and set it to 1 in the src URL

<iframe width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0" allowfullscreen></iframe>

b.给它一个唯一的ID

b. Give it a unique id

<iframe id="youtube-video" width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0" allowfullscreen></iframe>

c.加载 YouTube iFrame API

c. Load YouTube iFrame API

<script src="https://www.youtube.com/iframe_api"></script>

d.创建一个引用现有 iFrame 的播放器

d. Create a player that references the existing iFrame

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆