YouTube Data API v3 (DotNet) 编译和字幕下载代码使用示例

背景:

YouTube Data API v3 是可以用来管理youtube 上的视频的开放接口API,可以进行增删改查,以及用于服务器端管理大企业客户中的资源的对接API,在当今短视频爆火的年代,许多的国人通过借鉴Google 的YouTube,多国语言翻译,云API等制作了许多有用的工具。

下面演示一个.Net C#实现的字幕下载(翻译)程序范例(googleapis/google-api-dotnet-client):

前面是流程,后面附录有代码,如果编译不过,可以根据报错来查对应的解决方案。

1.需要申请一个Google API Key,以及一个 OAuth 2.0 客户端 ID

2. 有需要的可以先查阅一下开发者文档https://developers.google.com/youtube/documentation?hl=zh-cn   https://developers.google.com/youtube/documentation?hl=zh-cn

重要的开发步骤是先下载 GitHub - googleapis/google-api-dotnet-client: Google APIs Client Library for .NET

这里说明一下,Google的应用层API  支持比较多的语言,还有以下几种语言,

3.下载完成后,按照 google-api-dotnet-client-1.57.0\Src\Generated\Google.Apis.YouTube.v3 这个路径打开对应的工程文件:注意:这个工程主要是生成库文件,结构如下,需要创建一个Program.cs 文件:

对于如何将库生成工程转换成对应的生成应用程序的工程,一共需要有两个步骤,第一步,需要设置工程的属性,具体方式如下:

第二步 需要在生成应用程序的.cs 文件中,生成静态的Main 函数,具体如下,就能够用库文件工程生成引用程序了:

 4.先上代码,Program.cs 代码如下,细节内容可以见注释,具体的API 调用流程见如下的

 https://developers.google.com/youtube/v3/docs?hl=zh-cn  API文档

using Google.Apis.Auth.OAuth2;
using Google.Apis.Download;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Google.Apis.YouTube.v3
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                new Program().Run().Wait();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    Console.WriteLine("Error:" + e.Message);
                }
            }

        }


        private async Task Run()
        {
            //第一步鉴权,会自动拉起浏览器 授权
            UserCredential credential;
            //这个是client_secret.json 文件的路径,对应第一步中谷歌申请的   OAuth 2.0 客户端 ID 凭据 下载下来就是一个json 文件,记得替换一下路径
            string FilePath = "E:/DownLoad/google-api-dotnet-client-1.57.0/google-api-dotnet-client-1.57.0/Src/Generated/Google.Apis.YouTube.v3";
            FilePath = System.IO.Path.Combine(FilePath, "client_secret.json");
            using (var gstream = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(gstream).Secrets,
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
//注意这个地方 必须要选择 YouTubeService.Scope.YoutubeForceSsl  这个scope https://www.googleapis.com/auth/youtube.force-ssl
//https://www.googleapis.com/auth/youtubepartner
                    new[] { YouTubeService.Scope.YoutubeForceSsl },
                    "user",
                    CancellationToken.None
                );
            }

            //第二步,创建一个Youtube Service
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });
 
            string Id = "jBN2_YuTclU";
            //第三步 注意 要先通过Youtube 视频的ID  https://www.youtube.com/watch?v=v630bhaz8yU    V= 后面表示的就是视频的ID  这个跟字幕的ID 不是同一个
            //意思是查询视频的字幕 ID 列表   相当于这个 GET https://www.googleapis.com/youtube/v3/captions/id 请求 
            var ListRequest  = youtubeService.Captions.List("Id",Id);
            //这里是同步执行的请求
            var ListResponse = ListRequest.Execute();
            List<string> IdList = new List<string>();
            foreach (var Item in ListResponse.Items)
            {
                IdList.Add(Item.Id);
                Console.WriteLine("ItemId: " + Item.Id + " Item Kind:" + Item.Kind);
            }

            int Count = IdList.Count;
            if (Count == 0)
            {
                return;
            }

          //通过查询到的 字幕ID  这个跟视频ID 不一样  进行字幕的下载
            for (int i = 0;i< Count;i++)
            {
                string LoadedId = IdList[i];
                Console.WriteLine("Loaded Id: " + LoadedId);
                //这个是下载请求  注意  目前Youtube 只能下载 当前账户授权名下 的视频的字幕翻译和设置了允许 下载字幕的视频
                var DownloadRequest = youtubeService.Captions.Download(LoadedId);
                //这个是 ISO 639.2 两个字母表示的语言种类,其他国家的语言码具体查询  http://www.loc.gov/standards/iso639-2/php/code_list.php 
                DownloadRequest.Tlang = "en";
                //表示按照 SRT 格式的字幕下载
                DownloadRequest.Tfmt = "srt";
                string Path = System.IO.Path.Combine(Environment.CurrentDirectory, LoadedId + ".srt");
                Console.WriteLine("Path:" + Path);
                Stream stream = DownloadRequest.ExecuteAsStream();
                using (var fileStream = File.Create(Path))
                {
                    //保存下载好的字幕  文件SRT   后续可以在ffmpeg 工具或者三方的视频剪辑工具中使用
                    await stream.CopyToAsync(fileStream);
                }
            }
        }
    }

}

具体的代码和生成的程序如下(oauth2 记得替换 client_secret.json 需要按照第一步下载):

链接:https://pan.baidu.com/s/1Lv-1EYekP2eTowNsBnHcMw?pwd=tdmh 
提取码:tdmh 
 

程序在这个里面:

 

 

当然Google还有海量的其他API可供使用,具体的可以自行探索

 

 

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值