如何使用 Google.Apis.YouTube.v3 和 C# 将视频上传到 youtube? [英] How to upload Video to youtube using Google.Apis.YouTube.v3 and C#?

查看:37
本文介绍了如何使用 Google.Apis.YouTube.v3 和 C# 将视频上传到 youtube?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 C# 创建了 console 应用程序.它将upload Video 从本地驱动器上传到youtube.我使用 此链接在 google api 中创建了新应用.我还使用 nuget 安装了所有必需的 packages.当我运行我的应用程序时,我收到错误消息拒绝访问",我找不到问题.

我在 Task Run() 方法中遇到错误.

使用系统;使用 System.IO;使用 System.Reflection;使用 System.Threading;使用 System.Threading.Tasks;使用 Google.Apis.Auth.OAuth2;使用 Google.Apis.Services;使用 Google.Apis.Upload;使用 Google.Apis.Util.Store;使用 Google.Apis.YouTube.v3;使用 Google.Apis.YouTube.v3.Data;命名空间 Google.Apis.YouTube.Samples{///<总结>///YouTube 数据 API v3 示例:创建播放列表.///依赖于 .NET v1.7.0 或更高版本的 Google API 客户端库.///见 https://developers.google.com/api-client-library/dotnet/get_started///</总结>内部类 PlaylistUpdates{[STAThread]静态无效主(字符串 [] args){Console.WriteLine("YouTube 数据 API:播放列表更新");Console.WriteLine("==================================");尝试{new PlaylistUpdates().Run().Wait();}捕获(聚合异常前){foreach (var e in ex.InnerExceptions){Console.WriteLine("错误:" + e.Message);}}Console.WriteLine("按任意键继续...");Console.ReadKey();}私有异步任务运行(){UserCredential 凭证;使用 (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)){凭据 = 等待 GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,//此 OAuth 2.0 访问范围允许对//经过身份验证的用户帐户.new[] { YouTubeService.Scope.Youtube },用户",CancellationToken.None,新的 FileDataStore(this.GetType().ToString()));}var youtubeService = new YouTubeService(new BaseClientService.Initializer(){HttpClientInitializer = 凭证,ApplicationName = this.GetType().ToString()});//在授权用户的频道中创建一个新的私有播放列表.var newPlaylist = new Playlist();newPlaylist.Snippet = new PlaylistSnippet();newPlaylist.Snippet.Title = "测试播放列表";newPlaylist.Snippet.Description = "使用 YouTube API v3 创建的播放列表";newPlaylist.Status = new PlaylistStatus();newPlaylist.Status.PrivacyStatus = "public";newPlaylist = await youtubeService.Playlists.Insert(newPlaylist, "snippet,status").ExecuteAsync();//将视频添加到新创建的播放列表中.var newPlaylistItem = new PlaylistItem();newPlaylistItem.Snippet = new PlaylistItemSnippet();newPlaylistItem.Snippet.PlaylistId = newPlaylist.Id;newPlaylistItem.Snippet.ResourceId = new ResourceId();newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video";newPlaylistItem.Snippet.ResourceId.VideoId = "GNRMeaz6QRI";newPlaylistItem = await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync();Console.WriteLine("播放列表项 id {0} 已添加到播放列表 id {1}.", newPlaylistItem.Id, newPlaylist.Id);}}}

我需要将user"参数传递给 gmail 用户名吗?

任何使用 C#(控制台/网络)的工作示例?

感谢帮助.

解决方案

感谢@iedoc 的代码和答案

一个>

一个基本的 Web 项目示例

默认.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="服务器"><title>测试</title><身体><form id="form1" runat="server"><div><p><asp:TextBox runat="server" ID="videoName" placeholder="视频标题"/></p><p><asp:TextBox runat="server" ID="videoDesc" placeholder="视频描述"/></p><p><asp:FileUpload ID="videoUpload" runat="server"/></p><p><asp:Button id="saveDetails" Text="Update Chapel Group" runat="server" OnClick="saveDetails_click"/></p>

</表单>

默认.aspx.cs

使用系统;使用 System.IO;使用 System.Reflection;使用 System.Threading;使用 System.Threading.Tasks;使用 Google.Apis.Auth.OAuth2;使用 Google.Apis.Services;使用 Google.Apis.Upload;使用 Google.Apis.Util.Store;使用 Google.Apis.YouTube.v3;使用 Google.Apis.YouTube.v3.Data;使用 Google.Apis.Auth.OAuth2.Flows;使用 Google.Apis.Auth.OAuth2.Responses;公共部分类 _Default : System.Web.UI.Page{字符串 vID = "无";public void Page_Load(对象发送者,EventArgs e){}protected void saveDetails_click(object sender, EventArgs e){if (Path.GetFileName(videoUpload.PostedFile.FileName) != ""){YouTubeUtilities ytU = new YouTubeUtilities("REFRESH", "SECRET", "CLIENT_ID");//在此处传递您的 API 代码using (var fileStream = videoUpload.PostedFile.InputStream)//选中的帖子文件{vID = ytU.UploadVideo(fileStream,videoName.Text,videoDesc.Text,"22",false);}Response.Write(vID);}}}公开课 YouTubeUtilities{/*获取刷新令牌的说明:* https://stackoverflow.com/questions/5850287/youtube-api-single-user-scenario-with-oauth-uploading-videos/8876027#8876027** 获取client_id和client_secret时,使用已安装的应用程序,其他(这将使令牌成为长期令牌)*/私人字符串 CLIENT_ID { 获取;放;}私人字符串 CLIENT_SECRET { 获取;放;}私人字符串REFRESH_TOKEN { 获取;放;}私人字符串 UploadedVideoId { 获取;放;}私人 YouTube 服务 youtube;公共 YouTubeUtilities(String refresh_token, String client_secret, String client_id){CLIENT_ID = client_id;CLIENT_SECRET = client_secret;REFRESH_TOKEN = 刷新令牌;youtube = BuildService();}私人 YouTubeService BuildService(){ClientSecrets 机密 = 新 ClientSecrets(){ClientId = CLIENT_ID,ClientSecret = CLIENT_SECRET};var token = new TokenResponse { RefreshToken = REFRESH_TOKEN };var 凭据 = 新用户凭据(新 GoogleAuthorizationCodeFlow(新的 GoogleAuthorizationCodeFlow.Initializer{ClientSecrets = 秘密}),用户",令牌);var service = new YouTubeService(new BaseClientService.Initializer(){HttpClientInitializer = 凭据,应用程序名称 = "测试项目"});//service.HttpClient.Timeout = TimeSpan.FromSeconds(360);//选择你喜欢的超时时间退货服务;}public String UploadVideo(Stream stream, String title, String desc, String categoryId, Boolean isPublic){var video = new Video();video.Snippet = new VideoSnippet();video.Snippet.Title = 标题;video.Snippet.Description = desc;video.Snippet.CategoryId = categoryId;//参见 https://developers.google.com/youtube/v3/docs/videoCategories/listvideo.Status = new VideoStatus();video.Status.PrivacyStatus = isPublic ?公开":不公开";//私人"或公共"或不公开//var videosInsertRequest = youtube.Videos.Insert(video, "snippet,status", stream, "video/*");var videoInsertRequest = youtube.Videos.Insert(video, "snippet,status", stream, "video/*");videoInsertRequest.ProgressChanged += insertRequest_ProgressChanged;videoInsertRequest.ResponseReceived += insertRequest_ResponseReceived;视频插入请求.上传();返回 UploadedVideoId;}void insertRequest_ResponseReceived(视频视频){UploadedVideoId = video.Id;//video.ID 为您提供 Youtube 视频的 ID.//您可以从以下位置访问视频//http://www.youtube.com/watch?v={video.ID}}void insertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress 进度){//您可以在此处处理多个状态消息.开关(进度.状态){案例 UploadStatus.Failed:UploadedVideoId = "失败";休息;案例 UploadStatus.Completed:休息;默认:休息;}}}

我讨厌 .NET,并且我已经为此奋斗了几个星期.我遇到的一些问题;

  1. 一对有问题的 API 密钥,它们无法正常工作.我想这是一个随机错误.
  2. 我还有一些从 Youtube 下载的 MP4 无法上传,在创作者工作室中,他们会说上传失败:无法处理文件"我通过尝试在 youTube 界面中上传它们来确定这一点.(不是通过 API)
  3. 异步与同步给我带来了许多我不明白的问题.

我想改进此代码以提供实际的上传状态/反馈,但我认为这需要在客户端完成.我不太擅长 C#/.NET

UPDATE 这是我通过服务器的反馈代码 &客户端 - https://stackoverflow.com/a/49516167/3790921

I have created console application using C#. Which will upload Video from local drive to youtube. I have created new app in google api using this link. I have also installed all required packages using nuget. When I run my application I am getting error as "Access Denied" I am not able to find the issue.

I am getting error in Task Run() method.

using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

namespace Google.Apis.YouTube.Samples
{
  /// <summary>
  /// YouTube Data API v3 sample: create a playlist.
  /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
  /// See https://developers.google.com/api-client-library/dotnet/get_started
  /// </summary>
  internal class PlaylistUpdates
  {
    [STAThread]
    static void Main(string[] args)
    {
      Console.WriteLine("YouTube Data API: Playlist Updates");
      Console.WriteLine("==================================");

      try
      {
        new PlaylistUpdates().Run().Wait();
      }
      catch (AggregateException ex)
      {
        foreach (var e in ex.InnerExceptions)
        {
          Console.WriteLine("Error: " + e.Message);
        }
      }

      Console.WriteLine("Press any key to continue...");
      Console.ReadKey();
    }

    private async Task Run()
    {
      UserCredential credential;
      using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
      {
        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            // This OAuth 2.0 access scope allows for full read/write access to the
            // authenticated user's account.
            new[] { YouTubeService.Scope.Youtube },
            "user",
            CancellationToken.None,
            new FileDataStore(this.GetType().ToString())
        );
      }

      var youtubeService = new YouTubeService(new BaseClientService.Initializer()
      {
        HttpClientInitializer = credential,
        ApplicationName = this.GetType().ToString()
      });

      // Create a new, private playlist in the authorized user's channel.
      var newPlaylist = new Playlist();
      newPlaylist.Snippet = new PlaylistSnippet();
      newPlaylist.Snippet.Title = "Test Playlist";
      newPlaylist.Snippet.Description = "A playlist created with the YouTube API v3";
      newPlaylist.Status = new PlaylistStatus();
      newPlaylist.Status.PrivacyStatus = "public";
      newPlaylist = await youtubeService.Playlists.Insert(newPlaylist, "snippet,status").ExecuteAsync();

      // Add a video to the newly created playlist.
      var newPlaylistItem = new PlaylistItem();
      newPlaylistItem.Snippet = new PlaylistItemSnippet();
      newPlaylistItem.Snippet.PlaylistId = newPlaylist.Id;
      newPlaylistItem.Snippet.ResourceId = new ResourceId();
      newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video";
      newPlaylistItem.Snippet.ResourceId.VideoId = "GNRMeaz6QRI";
      newPlaylistItem = await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync();

      Console.WriteLine("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, newPlaylist.Id);
    }
  }
}

Do I need to pass 'user' parameter the gmail username?

Any working example using C# (console/web) ?

Help Appreciated.

解决方案

All Credit to @iedoc for his code and answer here

A basic working Web project example

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>testing</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p><asp:TextBox runat="server" ID="videoName" placeholder="Video Title" /></p>
        <p><asp:TextBox runat="server" ID="videoDesc" placeholder="Video Description" /></p>
        <p><asp:FileUpload ID="videoUpload" runat="server" /></p>
        <p><asp:Button id="saveDetails" Text="Update Chapel Group" runat="server" OnClick="saveDetails_click" /></p>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;

public partial class _Default : System.Web.UI.Page
{
    string vID = "none";
    public void Page_Load(object sender, EventArgs e)
    {

    }
    protected void saveDetails_click(object sender, EventArgs e)
    {
        if (Path.GetFileName(videoUpload.PostedFile.FileName) != "")
        {
            YouTubeUtilities ytU = new YouTubeUtilities("REFRESH", "SECRET", "CLIENT_ID"); // pass in your API codes here

            using (var fileStream = videoUpload.PostedFile.InputStream) // the selected post file
            {
                vID = ytU.UploadVideo(fileStream,videoName.Text,videoDesc.Text,"22",false);
            }
            Response.Write(vID);
        }

    }
}
public class YouTubeUtilities
{
    /*
     Instructions to get refresh token:
     * https://stackoverflow.com/questions/5850287/youtube-api-single-user-scenario-with-oauth-uploading-videos/8876027#8876027
     * 
     * When getting client_id and client_secret, use installed application, other (this will make the token a long term token)
     */
    private String CLIENT_ID { get; set; }
    private String CLIENT_SECRET { get; set; }
    private String REFRESH_TOKEN { get; set; }

    private String UploadedVideoId { get; set; }

    private YouTubeService youtube;

    public YouTubeUtilities(String refresh_token, String client_secret, String client_id)
    {
        CLIENT_ID = client_id;
        CLIENT_SECRET = client_secret;
        REFRESH_TOKEN = refresh_token;

        youtube = BuildService();
    }

    private YouTubeService BuildService()
    {
        ClientSecrets secrets = new ClientSecrets()
        {
            ClientId = CLIENT_ID,
            ClientSecret = CLIENT_SECRET
        };

        var token = new TokenResponse { RefreshToken = REFRESH_TOKEN };
        var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
            new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = secrets
            }),
            "user",
            token);

        var service = new YouTubeService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credentials,
            ApplicationName = "TestProject"
        });

        //service.HttpClient.Timeout = TimeSpan.FromSeconds(360); // Choose a timeout to your liking
        return service;
    }

    public String UploadVideo(Stream stream, String title, String desc, String categoryId, Boolean isPublic)
    {
        var video = new Video();
        video.Snippet = new VideoSnippet();
        video.Snippet.Title = title;
        video.Snippet.Description = desc;
        video.Snippet.CategoryId = categoryId; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
        video.Status = new VideoStatus();
        video.Status.PrivacyStatus = isPublic ? "public" : "unlisted"; // "private" or "public" or unlisted

        //var videosInsertRequest = youtube.Videos.Insert(video, "snippet,status", stream, "video/*");
        var videosInsertRequest = youtube.Videos.Insert(video, "snippet,status", stream, "video/*");
        videosInsertRequest.ProgressChanged += insertRequest_ProgressChanged;
        videosInsertRequest.ResponseReceived += insertRequest_ResponseReceived;

        videosInsertRequest.Upload();

        return UploadedVideoId;
    }

    void insertRequest_ResponseReceived(Video video)
    {
        UploadedVideoId = video.Id;
        // video.ID gives you the ID of the Youtube video.
        // you can access the video from
        // http://www.youtube.com/watch?v={video.ID}
    }

    void insertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
    {
        // You can handle several status messages here.
        switch (progress.Status)
        {
            case UploadStatus.Failed:
                UploadedVideoId = "FAILED";
                break;
            case UploadStatus.Completed:
                break;
            default:
                break;
        }
    }
}

I hate .NET and I have been fighting with this for weeks. Some of the problems I encountered;

  1. a faulty pair of API Keys, they just didn't work. I guess it was a random bug.
  2. I also have a couple MP4's that I downloaded from Youtube that would not upload back, within creator studio they would say "Upload failed: Can't process file" I determined this by attempting to upload them in the youTube interface. (not through API)
  3. async vs. synchronous was causing me many issues I just don't understand.

I would like to improve this code to provide actual upload status/feedback but I think that would need to be done client side. I am not very good at C#/.NET

UPDATE here is my feedback code via server & client side - https://stackoverflow.com/a/49516167/3790921

这篇关于如何使用 Google.Apis.YouTube.v3 和 C# 将视频上传到 youtube?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆