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.
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.
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
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);
//textbox1 contains username and maskedTextBox1 contains password
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.
YouTubeService
setUserCredentials
QueryClientLoginToken()
string
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:
clientlogin
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.
YouTubeRequest
YoutubeRequestSettings
YouTubeRequest
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: "" Video ID represents a particular video. This URL returns a particular video entry.
Related Videos Feed: "". Every video entry consists related video entries.
Responses feed: "".
Standard every few minutes.
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.
regionID
time
category
feedID
User's favorite feed: "" - This link is used when you want to access or modify the entries of user.
"" - This link is used when you want to access another users entries.
User's Playlist Feed: "" - This displays playlist information. This link is used to modify the playlist data.
"" - This link is used to access another users playlists.
To display video feeds, first we need feedURL (discussed above). In the project, I used GetfeedUrl function to get feedurl for standard feeds.
feedURL
GetfeedUrl
feedurl
string tempUrl,tfeedUrl,ttimeUrl,tcatUrl;
tempUrl = "";
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:
feedUrl
tempUrl=""
tfeedUrl="top_rated" , tcatUrl="" and ttimeUrl="?time=today". Now feedurl is
tempurl+tfeedurl+tcaturl+ttimeurl.
i.e. "".
Once you get the feedurl, now you can display the feeds using the URL. The following code shows how to display using feedUrl.
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.
get
Feed<video>
Listview
ListDisplay(entry)
listview
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.
for
ListDisplay()
ListDisplay
To play video click on thumbnail, it passes videoId to shockwave object used to play the videos.
videoId
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.
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.
MediaThumbnail
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 = ""+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.
playlistfeed
cmbSubservice
playlistfeed
ind
videofeed
DisplayFeed()
videofeed.totalresults
DisplayFeed()
Uri Url = new Uri("" + 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.
Getcomments(video)
Comment
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.
sindex
videofeed.start-index
To navigate to previous page, just negate the sindex.
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.
i
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
General News Suggestion Question Bug Answer Joke Rant Admin
Math Primers for Programmers