Working with the Youtube API

I recently began working on a new side-project, Youtube watch together. It solves that little irritation of syncing up your video with friends when the two of you are try watching it over the phone or Skype. The goal’s to make sure you never recite ‘3, 2, 1, play’ together trying to get your videos synced up.

As a precursor to sharing the development process of the app, I’m going to get you familiar with working with the youtube api — in particular the youtube iframe api. The iframe api lets you load a youtube video in an iframe and directly manipulate the video with javascript. This opens up a wealth of possibilities and especially provides the tools you need to sync up videos across different clients

To begin we add a div with the id ‘player’ to our html.

<div id=”player”></div>

The api will dynamically replace the div with the iframe that contains the video player

Now turning to the javascript.

var scripttag = document.createElement(‘script’);
scripttag.src = “https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName(‘script’)[0];
firstScriptTag.parentNode.insertBefore(scripttag, firstScriptTag);

Here we dynamically insert the api’s script tag to ensure it’s loaded asynchronously. We could use the async tag in the script to do the same but this approach gives more protection against failure on older browsers.

var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player(‘player’, {
        height: ‘390',
        width: ‘640',
        videoId: ‘M7lc1UVf-VE’,
        events: {
            ‘onReady’: onPlayerReady,
            ‘onStateChange’: onPlayerStateChange
        }
    });
}

We create a global variable ‘player’ and once onYouTubeIframeAPIReady is called ‘player’ is set to the new player element. onYouTubeIframeAPIReady() is called immediately on the loading of the iframe (by the api code found at https://www.youtube.com/iframe_api we added dynamically earlier)

We define the declared function onPlayerReady() which is called when the video player’s ready

function onPlayerReady(event) {
event.target.playVideo();
}

And call the method on the argument event playerVideo() to play.

There are numerous methods on the video object to play with — to allow playlists, skipping (player.seekTo()), playback rate (player.getPlaybackRate():Number) which you can explore here https://developers.google.com/youtube/iframe_api_reference

This should give you the grounding to build your own simple app with the youtube api and follow along with the build out of Youtube watch together.

Show your support

Clapping shows how much you appreciated Will Sentance’s story.