May 14, 2015
88 Views

YouTube Tutorial – The Player API

Written by

Dozens of video sharing sites may offer streaming video that plays back in higher quality than YouTube, but if you want eyeballs (and millions of them), then Google’s monstrously popular YouTube is the place to be.

For a long time, all you could do with YouTube as a web publisher was embed its hosted videos on your site. But thanks to a recent overhaul to the YouTube API, you can now do much more.

YouTube recently unveiled a new and improved Player API that allows developers to do things like re-skin the video player or create their own custom controls. In fact, if your scripting chops are up for it, you could build your own uploading interface for YouTube and then simultaneously post videos to YouTube and your site with one click of the mouse.

There are actually two different YouTube APIs — there’s the aforementioned Player API for skinning your embedded players and adding custom controls, plus the Data API for grabbing information about movies. Each API has a number of different functions.

We’re going to take a look at both the Data API and Player API on Webmonkey in this tutorial, but we’ll start with the Player API since it’s a little bit simpler to interact with.

Note: Many of the Player API’s new functions can be accessed through both JavaScript and ActionScript. We’ll take a look at the JavaScript controls, but the ActionScript API is very similar, so if you prefer ActionScript, you can convert this code without too much trouble.

Getting Started

When it come to embedding Flash, YouTube recommends using SWFObject, which is a JavaScript library for embedding Flash movies. Grab a copy of SWFObject and put it in your public web folder. Now include this line at the top of your page where you want to do your embedding:

 

<script type=”text/javascript” src=”/path/to/swfobject.js”></script> 

 

Now let’s embed a movie and start playing with the new API.

Using SWFObject

If you’ve never encountered SWFObject, you’re in for a treat. SWFObject greatly simplifies the process of embedding Flash movies, taking care of various cross-browser issues and other problems.

All you need to do is define a tag for SWFObject to replace with a Flash movie. Here’s some example HTML code you can use for this tutorial:

 

<body>
<div id="ytplayer">
<p>You will need Flash 8 or better to view this content.</p>
</div>

<script type="text/javascript">
	var params = { allowScriptAccess: "always" };
	swfobject.embedSWF(
		"http://www.youtube.com/v/tFI7JAybF6E&enablejsapi=1&playerapiid=ytplayer", "ytplayer", "425", "365", "8", null, null, params);
</script>
</body>


OK, here’s how it works.

First of all we create a div container to hold our embedded movie. If the user doesn’t have Flash 8 or better, they’ll see our plain paragraph text (note that SWFObject offers far more sophisticated ways of handling this, like auto-updating the users Flash player. See the documentation for full details).

The next step is to write the JavaScript and embed the movie. We’ve defined a params argument to tell Flash that it’s OK to let the YouTube domain load scripts, and then we call the embedSWF function.

The parameters passed to embedSWF include the location of the .swf file, the id of the tag we want to replace, the width and height of the video, the Flash Player version to require (the YouTube API requires version 8 or above) two parameters we’re not using and finally our params value.

Now let’s take a look at that URL was passed to embedSWF. For the most part, it’s an ordinary YouTube URL. But notice we’ve added two additional bits of data. We’ve told YouTube that we want to use the JavaScript API and we’ve given our player an API name.

The API name — in this case, “ytplayer” — is important because if you ever embed two movies on the same page and want to control them separately, each one needs to have a unique name.

Controlling the Player with JavaScript

If you load the above code in a browser, you’ll notice that you just Rickrolled yourself. Face! But more importantly, you’ll notice that the movie file doesn’t look any different than a normal embedded movie.

Let’s start adding some outside controls to our page so you can see how the Player API works. Go ahead and paste this function into your HTML, just below the SWFObject function:

 

function play() {
if (ytplayer) {
ytplayer.playVideo();
}
}

function pause() {
if (ytplayer) {
ytplayer.pauseVideo();
}
}

function stop() {
if (ytplayer) {
ytplayer.stopVideo();
}
}

 

 

Now just below the div element that we’re replacing, add this HTML code:

 

 

<a href="javascript:void(0);" onclick="play();">Play</a>

<a href="javascript:void(0);" onclick="pause();">Pause</a>

<a href="javascript:void(0);" onclick="stop();">Stop</a>

 

If you reload the page you’ll see that our HTML links can now control the player.

Now you might be thinking, what’s the point? After all the player already has controls. But if you’re trying to make embedded movies more closely match the look and feel of your site’s design, these tools make it easy to create your own controls.

So how to get rid of YouTube’s controls? Well, to do that we’ll need to use the “chromeless” player.

To use the chromeless player, our URL parameter inside the embedSWF function becomes something like:

 

http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer

 

Notice that we haven’t passed an actual movie id in this case. To do that with the chromeless player, we have to use the loadNewVideo function. So add this code below our other JavaScript functions:

 

function loadNewVideo(id, startSeconds) {
if (ytplayer) {
ytplayer.loadVideoById(id, startSeconds);
}
}

 

There are a number of ways we can call this function — through a drop down list of options, a text input box, etc. — but for simplicity’s sake, let’s just add another link button:

 

<a href=”javascript:void(0);” onclick=”loadNewVideo(‘tFI7JAybF6E’, 0);”>load</a>

 

And there you have it — a custom, chromeless movie player that you can control with JavaScript!

Conclusion

Now you know how to control and customize the basic YouTube movie player. Hopefully, you’ll also feel comfortable customizing the player to fit your own site.

If JavaScript isn’t your forte, there’s also a very similar (in function) ActionScript API that you can use to build your own controls and load chromeless players onto your pages.

Now you may be wondering, how can I get some YouTube movie data to display on my site? For instance, maybe you’d like to grab all the movies you’ve marked as favorites and display them on your blog? Or maybe you want to grab your own movies for display elsewhere.

We’ll cover those topics in our next installment when we tackle the other half of the YouTube API — The Data API.

Look for that tutorial on Webmonkey in just a few days.

_______________________________________________________

For those who want to dig deeper, welcome! It’s time to explore the YouTube Data API, which you can use to request and store info about movies you’d like to display on your site. You can pull in not only the videos themselves from YouTube, but also important metadata like the video title, tags, description, duration and so on.

Pick a Library

A variety of client libraries are available for the YouTube Data API, including:

We’ll be using Python for this tutorial. If you’re a PHP whiz or an old-school Java-head, you needn’t worry — the general concepts we’re going to cover will be the same no matter which language you use.

Get Started

Let’s say you frequently post movies to YouTube and you’re tired of cutting and pasting the embed code to get them to show up on your site.

Using the YouTube Data API and some quick Python scripts, we can grab all our movies — along with the metadata associated with the clips — and automatically add them our database. For instance, if you followed along with Webmonkey’s Django tutorial series, this technique would be a handy way to add YouTube to your list of data providers.

To get started, go ahead and download the Python YouTube Data Client Library. Follow the instructions for installing the Library as well as any required dependencies (in this case, ElementTree, which is only necessary if you aren’t running Python 2.5).

Just to make sure you’ve got everything set up correctly, fire up a terminal window, start Python and try importing the modules we need:

>>> import gdata.youtube

>>> import gdata.youtube.service

If those imports worked, you’re ready to start grabbing data.

Working with the YouTube Data API

The first thing we need to do is construct an instance of the YouTube Data service. Enter this code at the prompt:

yt_service = gdata.youtube.service.YouTubeService()

That’s a generic object with no authentication, so we can only retrieve public feeds. But for our purposes, that’s all we need. First, let’s write a function that can parse the data we’ll be returning.

Create a new text file named youtube_client.py and paste in this code:

import gdata.youtube

import gdata.youtube.service



class YoutubeClient:

    def __init__(self):

        self.yt_service = gdata.youtube.service.YouTubeService()



    def print_items(self, entry):

        print 'Video title: %s' % entry.media.title.text

        print 'Video published on: %s ' % entry.published.text

        print 'Video description: %s' % entry.media.description.text

        print 'Video category: %s' % entry.media.category[0].text

        print 'Video tags: %s' % entry.media.keywords.text

        print 'Video flash player URL: %s' % entry.GetSwfUrl()

        print 'Video duration: %s' % entry.media.duration.seconds

        print '----------------------------------------'



    def get_items(self, feed):

       for entry in feed.entry:

           self.print_items(entry)



Obviously, if you want to store the data you’re about to grab, you will need to rewrite the print_items function to do something other than just print out the data. But for the sake of example, and because there are a near infinite number of ways your database could be structured, we’ll just stick with a simple print function for now.

So make sure youtube_client.py is on your PythonPath and fire up Python again, then input these lines:

>>> from youtube_client import YoutubeClient

>>> client = YoutubeClient()

>>> client.get_items(client.yt_service.GetMostLinkedVideoFeed())

The last line should produce a barrage of output as the client prints out a list of most linked videos and all of the associated data for each clip. To get that list, we just used one of the YouTube service modules’ built-in methods, GetMostLinkedVideoFeed().

While that’s all well and good if you want the most linked videos on the entire YouTube site, what if you want something more specific? Say, your uploaded videos?

To get that list, we’re going to use another method of YouTube service module: the GetYouTubeVideoFeed() method.

Getting a List of Your Uploaded Videos

First, find the video feed URL for your YouTube account, which should look something like this:

http://gdata.youtube.com/feeds/api/users/YOURUSERNAME/uploads

Next, plug that into our already running client with these two lines:

url = 'http://gdata.youtube.com/feeds/api/users/YOURUSERNAME/uploads'

client.get_items(client.yt_service.GetYouTubeVideoFeed(url))

You should see a list of all your recently uploaded videos, along with all the metadata we plugged into our print_items() function.

Conclusion

Hopefully, this lesson has given you some insight into how YouTube’s Data API operates. We’ve really just scratched the surface — dozens of methods are available to retrieve all sorts of data — see the [Python YouTube Data API guide] for more details.

While we’ve used Python, the methods and techniques are essentially the same for all the client libraries, so you should be able to interact with YouTube using a language you’re comfortable with.

Obviously you’ll want to adjust the print_items() function we demonstrated to do something more useful than just printing the results. Like what, you ask?

If you’re using Django, you could create a model to hold all the data and then use the model’s get_or_create() method to plug the data in via print_items(). For full automation, you could also write a shell script to call the methods we used above and attach the script to a cron job.

Anyway, there you have it — an easy way to add YouTube videos to your own personal site with no manual labor on your end.

 

 

 

 

 

Article Tags:
· · · · · · · · · · · · · · · · · · · · · · · · ·
Article Categories:
Code/Web
    http://linholiver.com

    https://linholiver.com/diary/about/