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
915 views
in Technique[技术] by (71.8m points)

jquery - Check if YouTube video is playing and run script

I have the following video embeded within WordPress

<iframe id="video" width="640" height="360" src="http://www.youtube.com/embed/xxxxxx?enablejsapi=1" frameborder="0" allowfullscreen></iframe>

And it's inside a SlideDeck slider, which I want to stop when someone clicks the video. I can't figure out how to get this line of code

self.pauseAutoPlay = true;

to run when the video is playing.

I desperately need some help please.

Edit: As I'm not the end user. I need something that will work with the default embed code from YouTube.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You need to use the YouTube iFrame API. Keep in mind, I know just the bare basics of Javascript and so on so this could potentially be a lot more efficient.

You them embed your iframe as you normally would

<iframe id="player" width="640" height="360" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowfullscreen></iframe>

But with a couple changes. It needs to have an ID, 'player', and you need to append ?enablejsapi to the end of the source URI.

You'll then need to run the following script to load the API JS as well as creat the player

// 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');
      tag.src = "http://www.youtube.com/player_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'u1zgFlCw8Aw',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

Notice that new YT.Player('player' should match your iframe ID and that videoId: 'u1zgFlCw8Aw' should match the src URI.

After this you'll be able to run scripts like

var myPlayerState;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
          // DO THIS
        }
        myPlayerState = event.data;
      }

if (myPlayerState == 1){
  // PAUSE SLIDER
}

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

...