0

A feature I am trying to implement in my rails app is the ability for users to control embedded youtube videos. I am using the youtube player api (guidelines here: https://developers.google.com/youtube/iframe_api_reference).

In the guidelines, it is always creating a new YT player:

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

My question is how can I play an already embedded youtube video with an outside 'play' button. The error is on the player = new YT.Player line. I don't want to make a new player, just control the already embedded video.

var player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('video', {  
      events: {
        'onReady': onPlayerReady
      }
    });
}

function onPlayerReady(event){
  event.target.playVideo();
    document.id("start").click(function () {
      player.playVideo();
    });    

  }
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

my iframe:
<iframe title="YouTube video player" id="video" width="540" height="290" src="http://www.youtube.com/embed/#{ youtube_id }?rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>

header view with play button:

<div id="start">
  <%= image_tag("playback_play.png")  %>
</div>

(rails app)

if you need more code, let me know, thanks for the help!

Ox Smith
  • 509
  • 1
  • 7
  • 20
  • Try this in your – bunty Jun 09 '13 at 19:38
  • Just fund a duplicate question here, with a great answer: http://stackoverflow.com/questions/7443578/youtube-iframe-api-how-do-i-control-a-iframe-player-thats-already-in-the-html – Ox Smith Jun 09 '13 at 19:59

1 Answers1

0

Not a direct answer to your question, but a potential solution for you:

<div id="player"></div>
<div id="start" style="display: none;">
  <%= image_tag("playback_play.png")  %>
</div>

<script>
function onYouTubePlayerAPIReady() {
  player = new YT.Player('player', {
    height: '390',
    width: '640',
    videoId: '#{ youtube_id }', // not sure if you want that or <%= youtube_id %> in this case
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerReady(event){
  //event.target.playVideo(); // commented out -- uncomment if you want autoplay
  document.id("start").show();
}

var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>
Hamza Kubba
  • 2,259
  • 14
  • 12