Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

javascript - How do I get the reference to an existing YouTube player?

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

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.

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 question might be a duplicate of this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be done like the following.

Given a general YouTube embed source code:

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

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. 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. Load YouTube iFrame API

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

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");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...