如何创建基于 Youtube API 上传视频代码的 Azure Function?
Posted
技术标签:
【中文标题】如何创建基于 Youtube API 上传视频代码的 Azure Function?【英文标题】:How to create Azure Function based off Youtube API upload video code? 【发布时间】:2020-05-30 15:19:44 【问题描述】:我正在尝试转换此控制台应用程序:(https://developers.google.com/youtube/v3/docs/videos/insert),其中包含使用 YouTube API 将视频上传到 YouTube 的代码。 我正在尝试将此代码放入 Azure 函数 并使用 Azure Blob 存储来存储我的 YouTube 文件。
我从一个简单的 Http 触发 Azure 函数开始,然后慢慢开始在函数中插入更多代码,但是在我这样做的过程中,我遇到了各种错误。这是代码,我正在尝试将其插入到我的 Azure 函数中:
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: upload a video.
/// 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 UploadVideo
[STAThread]
static void Main(string[] args)
Console.WriteLine("YouTube Data API: Upload Video");
Console.WriteLine("==============================");
try
new UploadVideo().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 an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] YouTubeService.Scope.YoutubeUpload ,
"user",
CancellationToken.None
);
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;
await videosInsertRequest.UploadAsync();
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
switch (progress.Status)
case UploadStatus.Uploading:
Console.WriteLine("0 bytes sent.", progress.BytesSent);
break;
case UploadStatus.Failed:
Console.WriteLine("An error prevented the upload from completing.\n0", progress.Exception);
break;
void videosInsertRequest_ResponseReceived(Video video)
Console.WriteLine("Video id '0' was successfully uploaded.", video.Id);
【问题讨论】:
您遇到了哪些错误? 太多无法命名,但它们很少:找不到命名空间。另外,googlrwebauthorizationbtoker 不存在等等......我的问题是如何复制 YouTube 提供的代码示例并将其粘贴到中,作为 azure 函数? @Thiago Custodio,名字太多,但很少:找不到命名空间。另外,googlrwebauthorizationbtoker 不存在等等......我的问题是如何复制 YouTube 提供的代码示例并将其粘贴到中,作为 azure 函数? 只是复制和过去是行不通的。您需要导入包:Google.Apis.Auth.OAuth2; Google.Apis.Services; Google.Apis.上传; Google.Apis.Util.Store; Google.Apis.YouTube.v3; Google.Apis.YouTube.v3.Data; @Thiago Custodio,我也试过了。如果可能的话,您介意展示一下它应该如何设置吗? 【参考方案1】:共享包含在 Azure 函数中的格式化源代码,但请注意,您将无法按原样使用它,因为它试图从本地路径访问文件。您可以进一步重构它并将可访问的文件路径作为输入参数传递。
在编译成功之前需要安装几个 nuget 包/依赖项
public static class Function1
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
log.LogInformation("C# HTTP trigger function processed a request.");
log.LogInformation("YouTube Data API: Upload Video");
log.LogInformation("==============================");
try
await Run();
catch (AggregateException ex)
foreach (var e in ex.InnerExceptions)
log.LogInformation("Error: " + e.Message);
return new OkObjectResult($"Video Processed..");
private static 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 an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] YouTubeService.Scope.YoutubeUpload ,
"user",
CancellationToken.None
);
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;
await videosInsertRequest.UploadAsync();
private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
switch (progress.Status)
case UploadStatus.Uploading:
Console.WriteLine("0 bytes sent.", progress.BytesSent);
break;
case UploadStatus.Failed:
Console.WriteLine("An error prevented the upload from completing.\n0", progress.Exception);
break;
private static void videosInsertRequest_ResponseReceived(Video video)
Console.WriteLine("Video id '0' was successfully uploaded.", video.Id);
【讨论】:
当我在 Visual Studio 上本地运行 azure 函数时,我不断收到此错误:“Executed 'Function1' (Failed, Id=84400f0c-b6e4-4c78-bf55-30c4527a8b5f) System.Private。 CoreLib:执行函数时出现异常:Function1。System.Private.CoreLib:找不到文件'C:\Users\Peter\Desktop\TestDemo\UploadVideo\UploadVideo\bin\Debug\netcoreapp2.1\client_secrets.json'。”我不知道如何解决这个问题。以上是关于如何创建基于 Youtube API 上传视频代码的 Azure Function?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 C# 中的 Youtube API 将视频上传到 YouTube?
创建发布 apk 时 Youtube 数据 API v3 不上传视频
上传视频和缩略图 - YouTube Data API Python
YouTube 频道中的“已发布视频”和“上传”有啥区别?以及如何通过 YouTube Data v3 API 获取它们?