List YouTube videos using C# and Google.Apis.YouTube.v3

隐身守侯 提交于 2019-12-03 10:08:54

问题


I'm trying to perform some YouTube video interaction using the latest version of Google.Apis.YouTube.v3 (as of Jan 15, 2014).

I have done a NuGet on the following:

  • Google.Apis.YouTube.v3
  • Google.Apis.Authentication
  • Google.Apis.Drive.v2 (not necessary, but got it anyways)

I then attempted to run the code found on: https://developers.google.com/youtube/v3/docs/playlistItems/list

However, the code has the following references which I can't seem to find in any of the latest NuGet downloads...

  • using Google.Apis.Auth.OAuth2.DotNetOpenAuth;
  • using Google.Apis.Samples.Helper;

Then there's the following comment at the top of the code, but the links lead me to nothing useful.

/* External dependencies, OAuth 2.0 support, and core client libraries are at: */ /* https://code.google.com/p/google-api-dotnet-client/wiki/APIs#YouTube_Data_API */ /* Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at: */ /* https://code.google.com/p/google-api-dotnet-client/wiki/Downloads */

I'm beginning to believe the best way to play with YouTube using C# is to use older versions of the YouTube.v3 codebase that coincide with examples folks have seemed to get working.

Any help (esp from peleyal) would be much appreciated. Perhaps I'm missing something obvious and need to be beat over the head...

BTW, I have downloaded my client secret json file and successfully run a few of the examples contained within the google-api-dotnet-client-1.7.0-beta.samples.zip file. However, strangely missing from that samples zip file are any YouTube samples. Also missing from that zip file is the Google.Apis.Samples.Helper classes.

Does anyone have some useful example code for interacting with YouTube using the latest NuGet code as of Jan 14, 2014?


回答1:


So after much research, digging and a little less hair, I figured out a few things.

First, log into the "Google Cloud Console". If you're using GAE (Google App Engine) and you click on your GAE project and enable the "YouTube Data API v3", you are guaranteed to get NO WHERE! Instead, back out of your GAE project, and create a new Project called "API Project" for example.

Then within that project, enable your desired API's and you'll begin to get better results. Much better results. Start first with trying a YouTube search. This allows you to just insert your API key and you don't have to mess with OAuth2 and it requires less dll's, so its a good place to start. Try something like the following:

YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer() {
    ApplicationName = "{yourAppName}",
    ApiKey = "{yourApiKey}",
});
SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
listRequest.Q = "Loeb Pikes Peak";
listRequest.MaxResults = 5;
listRequest.Type = "video";
SearchListResponse resp = listRequest.Execute();
foreach (SearchResult result in resp.Items) {
    CommandLine.WriteLine(result.Snippet.Title);
}

Feel free to replace CommandLine with regular Console print stmts.

Next, move on to OAuth 2.0 and try to get your credentials to go through without erroring. You'll need to download your OAuth JSON file from "Google Cloud Console" under the "Credentials" section. Once you have this file, replace any files named "client_secrets.json" with the contents of the downloaded json file. In order to get the authorization to work, I found that I was missing the Microsoft.Threading.Tasks.Extensions.Desktop.dll which is the dll that allows the browser to open a window to grant access for the Native Application to muck with your YouTube acct. So if you have some errors during the Authorization part, check the inner exception and there's a chance that might be your issue as well.

Disclaimer: The bottom half of the code shown below was snarfed from: github.com/youtube/api-samples/blob/master/dotnet

UserCredential credential;
using (FileStream stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
        "user",
        CancellationToken.None,
        new FileDataStore("YouTube.Auth.Store")).Result;
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer() 
{
    HttpClientInitializer = credential,
    ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "Default Video Title";
video.Snippet.Description = "Default Video Description";
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
var filePath = @"REPLACE_ME.mp4"; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
    videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
    videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
    videosInsertRequest.UploadAsync();
}

So there's my 2 cents worth. Also, you'll need to do a NuGet on DotNetOpenAuth and within your code, replace any "using" calls to Google.Apis.Auth.OAuth2.DotNetOpenAuth to just "using DotNetOpenAuth".

Hopefully this helps others. The big thing was figuring out the GAE versus a new project. Once I figured that out, normal amounts of research started yielding results rather than pure frustration!!



来源:https://stackoverflow.com/questions/21132531/list-youtube-videos-using-c-sharp-and-google-apis-youtube-v3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!