Introduction
This is my first article. So please guide me to correct my mistakes.
This code shows how to access Youtube from desktop. Here you can perform same actions that can be done in Youtube. Here I used YouTube API 1.6. Please download the same version. In the latest version, you will get some error when running the code.
Using the Code
This is a client application which interacts with Youtube using Youtube API 1.6 .NET client library. In this article, I will explain about authentication, video feeds, displaying feeds and pagination.
Basic Requirements
- .NET 2.0 runtime
- Youtube API 1.6 SDK
- Developer key (you can get it from http://code.google.com/apis/youtube/dashboard/)
- Video player to play the video. You can use Windows media player or flash player. Here I used shockwave player to play the video.
After downloading and installing the Youtube SDK, go to Installed location and you will find the DLLs that you need to get started in the distribution's Redist sub directory. Then open your IDE and add reference to the DLLs (i.e., Google.Gdata.Client.dll, Google.Gdata.Extensions.dll, Google.Gdata.Youtube.dll).
Then, import the following namespaces:
using Google.GData.Extensions;
using Google.GData.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.YouTube
1: Authentication
To access Youtube from client application, first you need to authenticate yourself. The following code shows how to check whether the username and password are incorrect or not.
YouTubeService service = new YouTubeService();
service.setUserCredentials(textBox1.Text , maskedTextBox1.Text);
try{
service.QueryClientLoginToken();}
catch(System.Net.WebException e){MessageBox.Show(e.Message);}
To check the username and password, you need to create an instance of YouTubeService
. Constructor of the class contains 3 overloaded methods. Once the object is created, then use setUserCredentials
method to assign the username and password. Then call QueryClientLoginToken()
. This method returns a string
(token) that authenticates the user if the user credentials are correct. Else, it will throw System.Net.WebException
.
The token can also be used for further implementation of project. But in this project, I used it to check whether the username and password are correct or not. Then I passed it to the next window form to display feeds and search results.
I used Client Login Authentication for querying.
To use clientlogin
authentication, you must give correct username and password. Check the below code:
yousettings= new YouTubeRequestSettings("YouManager",devkey,username,password);
yourequest=new YouTubeRequest(yousettings);
The above code performs client login authentication. To perform every action, you need the Instance of YouTubeRequest
class. To create the instance, you need to pass settings, i.e., instance of YoutubeRequestSettings
class. To create a setting, you need to pass application name, developer key, username and password to the constructor. This setting can be used for YouTubeRequest
class. When you make a query, you need this instance of YouTubeRequest
. It will throw an exception if settings are incorrect.
2: Youtube Video Feeds
Youtube video feed is a regularly updated summary of videos along with other details like author, comments for videos, view count, etc. of the videos. In our application, we use video feeds to fetch the data. There are many types of feeds provided by Youtube API. They are Video feed, related videos feed, Video responses feed, Standard feed, Users favorite feed, Playlist feed.
General Syntax of Youtube video feeds:
Video feed: "http://gdata.youtube.com/feeds/api/videos/videoID" Video ID represents a particular video. This URL returns a particular video entry.
Related Videos Feed: "http://gdata.youtube.com/feeds/api/videos/videoID/related". Every video entry consists related video entries.
Responses feed: "http://gdata.youtube.com/feeds/api/videos/videoID/responses".
Standard Feeds: Standard feeds contain lists of videos that either reflect YouTube user behavior, such as top-rated and most viewed video feeds, or were selected by YouTube staff, such as recently featured and mobile video feeds. Many of these feeds are shown on the Videos tab of the YouTube website. Standard feeds are updated every few minutes.
http://gdata.youtube.com/feeds/api/standardfeeds/
regionID/
feedID_CATEGORY_NAME?time=timeID
In the above URL, you can see regionID
. Region ID is used to get specific videos of countries. If you enter region id as JP, you will get videos from Japan only. feedID specifies about type of feed, i.e., it may be top rated or most viewed, etc. category name is used to get videos from a particular category, i.e., comedy, sports, etc. timeID is used to get videos for specific time, i.e., it may be today, this week, this month or all time. And it is not necessary to mention regionID
, time
or category
name. But feedID
is necessary.
User's favorite feed: "http://gdata.youtube.com/feeds/aspi/users/default/favorites" - This link is used when you want to access or modify the entries of user.
"http://gdata.youtube.com/feeds/aspi/users/username/favorites" - This link is used when you want to access another users entries.
User's Playlist Feed: "http://gdata.youtube.com/feeds/api/users/default/playlist" - This displays playlist information. This link is used to modify the playlist data.
"http://gdata.youtube.com/feeds/api/users/username/playlist" - This link is used to access another users playlists.
3: Displaying Feeds
To display video feeds, first we need feedURL
(discussed above). In the project, I used GetfeedUrl
function to get feedurl
for standard feeds.
string tempUrl,tfeedUrl,ttimeUrl,tcatUrl;
tempUrl = "http://gdata.youtube.com/feeds/api/standardfeeds/";
tfeedUrl=tcatUrl =ttimeUrl = "";
switch (feed)
{
case 0:tfeedUrl="top_rated";break;
case 1: tfeedUrl = "top_favorites";break;
case 2: tfeedUrl = "most_viewed";break;
case 3: tfeedUrl = "most_popular";break;
case 4: tfeedUrl = "most_recent";break;
case 5: tfeedUrl = "most_discussed";break;
case 6: tfeedUrl = "most_responded";break;
case 7: tfeedUrl = "recently_featured";break;
}
switch (cat)
{
case 0: tcatUrl = "";break;
case 1: tcatUrl = "_Autos";break;
case 2: tcatUrl = "_Comedy";break;
case 3: tcatUrl = "_Education";break;
case 4: tcatUrl = "_Entertainment";break;
case 5: tcatUrl = "_Film";break;
case 6: tcatUrl = "_Howto";break;
case 7: tcatUrl = "_Music";break;
case 8: tcatUrl = "_News";break;
case 9: tcatUrl = "_People";break;
case 10: tcatUrl = "_Sports";break;
}
switch (time)
{
case 0: ttimeUrl = "?time=today";break;
case 1: ttimeUrl = "?time=this_week";break;
case 2: ttimeUrl = "?time=this_month";break;
case 3: ttimeUrl = "";break;
}
tempUrl = tempUrl + tfeedUrl + tcatUrl + ttimeUrl;
feedUrl = tempUrl;
The above code is used to get the feedUrl
. I used combo boxes to get the category feedtype and time. Example: I want to get videos from today's top rated videos, then feed URL will be like this:
tempUrl="http://gdata.youtube.com/feeds/api/standardfeeds/"
tfeedUrl="top_rated" , tcatUrl="" and ttimeUrl="?time=today". Now feedurl is
tempurl+tfeedurl+tcaturl+ttimeurl.
i.e. "http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?time=today".
Once you get the feedurl
, now you can display the feeds using the URL. The following code shows how to display using feedUrl
.
Feed<video> videofeed = yourequest.Get<Video>(new Uri(feedUrl));DisplayFeed();
public void DisplayFeed()
{
lvcount = 0;
lvDisplay.Items.Clear();
foreach (Video entry in videofeed.Entries)
{
ListDisplay(entry);
videocount++;
}
}
To display feed, first you need to create object of feed. Then you can assign video feeds by using get
method. Here, you use the YouTubeRequest
object to call get
method. The display feed function is used to display the feeds. The Feed<video>
object is a collection of videos. It contains a maximum of 25 videos. Hence, you need to display videos by using iterator entry. In this project, I used Listview
to display the video entries. ListDisplay(entry)
function is used to display each video entry. The image below shows the display in listview
control. The below diagram shows the listview
display.
With the help of for
loop, we pass a video object to the ListDisplay()
function. ListDisplay
function is used to display the contents of video. Every video object contains the following information. Title, Average rating, View count, Description, Author, VideoID, Commands count, medial location, thumbnail location, etc. Every video feed consists of 25 video entries maximum. Hence, I created a string
array of size 25 to store these details. When the user clicks on the list item, other things are displayed.
To play video click on thumbnail, it passes videoId
to shockwave object used to play the videos.
url+="&autoplay=1";
The above code can be used to play the video in autoplay mode. Here URL is taken from 1st entry of medialocation
.
foreach (Google.GData.YouTube.MediaContent mediaContent in video.Contents)
{
if (i == 1)break;
medialocations[lvcount] = mediaContent.Url;i++;
}
The above code is used to get medialocation
. Similarly, thumbnails can be taken using MediaThumbnail
object as an iterator.
Displaying feeds is easy but displaying Playlist information is slightly different. To display the contents of playlist, first you need to get playlist id.
int i = 0;playlistfeed = request.GetPlaylistsFeed(user);
foreach (Playlist pl in playlistfeed.Entries)
{
if (i == cmbSubService.SelectedIndex)
{
p = pl;
break;
}
i++;
}
string[] temp = p.Id.Split(':');
int ind = temp.GetUpperBound(0);
feedUrl = "http://gdata.youtube.com/feeds/api/playlists/"+temp[ind]+"?v=2";
videofeed = request.Get<Video>(new Uri(feedUrl));DisplayFeed();
The above code shows how to display the playlist contents. playlistfeed
contains the list of playlists of a particular user. Then using iterator, we can get each playlist. Here cmbSubservice
is combobox. Once you get a particular playlist from playlistfeed
, you need to store playlist id in a string
using split method. Here ind
specifies the id of playlist in string
array generated by split function. Then you can create the feedUrl
. Once you get the feedUrl
, you can get the contents using videofeed
and DisplayFeed()
function displays the playlist contents. Before calling DisplayFeed()
function, you must check whether the playlist contains any videos. videofeed.totalresults
will give the information about number of video entries. You can use it to check the playlist before calling DisplayFeed()
function.
Uri Url = new Uri("http://gdata.youtube.com/feeds/api/videos/" + videoID);
Video video = yourequest.Retrieve<Video>(Url);
Feed<Comment> comment = yourequest.GetComments(video);
rtComents.Text = "";
foreach (Comment c in comment.Entries)
{
rtComents.Text += c.Content + "\n";
}
The above code is used to display the comments for specific videos. First, you need to create a video URL. Next, create a video object. To receive comments, you need to create comment feed object using Getcomments(video)
function. It is a collection of comments, hence you need Comment
object as iterator to display the comments.
4: Pagination
Every feed contains only 25 videos. Hence, if you want to view more videos, you need to navigate through the pages. To make this happen, we need to use start-index feature of the feedUrl
. If you didn't mention start-index in feedUrl
, by default it is zero. Hence it can be used to display the other pages of feedUrl
.
sindex += 25;
if (feedUrl.Contains('?'))
{
tempUrl = feedUrl + "&start-index=" + sindex.ToString();
}
else
{
tempUrl = feedUrl + "?start-index=" + sindex.ToString();
}
videofeed = yourequest.Get<Video>(new Uri(tempUrl));
DisplayFeed();
The above code shows how to navigate to the next page. Here sindex
variable stores videofeed.start-index
, i.e., the first page. List display uses 25 video entries. Hence when you click on next page sindex
needs to be incremented by 25. Then it needs to be added to the feedUrl
. Once it is added, videofeed
stores the next set of videos. Using display feed method, we can display the next set of videos.
To navigate to previous page, just negate the sindex
.
To jump to the specific page, use the below code:
sindex = i * 25 + 1;
Here sindex
stores the start index. 25 means 25 videos displayed in a page. i
represents the page number to jump.
References
History
- 7th January, 2011: Initial post