如何在 .Net 中使用 Youtube Api v3 向 youtube 视频添加字幕
How to add captions to youtube video with YoutubeApi v3 in .Net
我在为上传到我公司的 YouTube 频道的视频添加字幕时遇到问题。我想在 .Net 中使用 Google 的 Youtube Api v3。我能够成功将视频上传到频道,但在尝试发送字幕时出现以下错误:
"System.Net.Http.HttpRequestException: Response status code does not indicate success: 403 (Forbidden)."
据我所知,我的凭据并未禁止我上传字幕。我可以毫无问题地上传视频。
我使用此处的说明创建了刷新令牌:
Youtube API single-user scenario with OAuth (uploading videos)
这是我用来创建 YouTubeService 对象的代码:
private YouTubeService GetYouTubeService()
{
string clientId = "clientId";
string clientSecret = "clientSecret";
string refreshToken = "refreshToken";
try
{
ClientSecrets secrets = new ClientSecrets()
{
ClientId = clientId,
ClientSecret = clientSecret
};
var token = new TokenResponse { RefreshToken = refreshToken };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets,
Scopes = new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload, YouTubeService.Scope.YoutubeForceSsl }
}),
"user",
token);
var service = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "TestProject"
});
service.HttpClient.Timeout = TimeSpan.FromSeconds(360);
return service;
}
catch (Exception ex)
{
Log.Error("YouTube.GetYouTubeService() => Could not get youtube service. Ex: " + ex);
return null;
}
}
这是我上传字幕文件的代码:
private void UploadCaptionFile(String videoId)
{
try
{
Caption caption = new Caption();
caption.Snippet = new CaptionSnippet();
caption.Snippet.Name = videoId + "_Caption";
caption.Snippet.Language = "en";
caption.Snippet.VideoId = videoId;
caption.Snippet.IsDraft = false;
WebRequest req = WebRequest.Create(_urlCaptionPath);
using (Stream stream = req.GetResponse().GetResponseStream())
{
CaptionsResource.InsertMediaUpload captionInsertRequest = _youtubeService.Captions.Insert(caption, "snippet", stream, "*/*");
captionInsertRequest.Sync = true;
captionInsertRequest.ProgressChanged += captionInsertRequest_ProgressChanged;
captionInsertRequest.ResponseReceived += captionInsertRequest_ResponseReceived;
IUploadProgress result = captionInsertRequest.Upload();
}
}
catch (Exception ex)
{
Log.Error("YouTube.UploadCaptionFile() => Unable to upload caption file. Ex: " + ex);
}
}
void captionInsertRequest_ResponseReceived(Caption obj)
{
Log.Info("YouTube.captionInsertRequest_ResponseReceived() => Caption ID " + obj.Id + " was successfully uploaded for this clip.");
Utility.UpdateClip(_videoClip);
}
void captionInsertRequest_ProgressChanged(IUploadProgress obj)
{
switch (obj.Status)
{
case UploadStatus.Uploading:
Console.WriteLine("{0} bytes sent.", obj.BytesSent);
break;
case UploadStatus.Failed:
Log.Error("YouTube.UploadCaptionFile() => An error prevented the upload from completing. " + obj.Exception);
break;
}
}
这几天我一直在研究这个问题,但一直没有取得任何进展。 YouTubeApi v3 没有太多关于添加字幕的信息。我所能找到的只是 v2 的一些旧信息,这需要一些 POST 调用,这些调用需要我没有的密钥。我希望能够使用 API 的内置方法添加字幕。
如果有人有处理此问题的经验,我将不胜感激你能提供的任何帮助。
编辑:
这是我将视频发送到 YouTube 的代码。
public string UploadClipToYouTube()
{
try
{
var video = new Google.Apis.YouTube.v3.Data.Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = _videoClip.Name;
video.Snippet.Description = _videoClip.Description;
video.Snippet.Tags = GenerateTags();
video.Snippet.DefaultAudioLanguage = "en";
video.Snippet.DefaultLanguage = "en";
video.Snippet.CategoryId = "22";
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "unlisted";
WebRequest req = WebRequest.Create(_videoPath);
using (Stream stream = req.GetResponse().GetResponseStream())
{
VideosResource.InsertMediaUpload insertRequest = _youtubeService.Videos.Insert(video, "snippet, status", stream, "video/*");
insertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
insertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
insertRequest.Upload();
}
return UploadedVideoId;
}
catch (Exception ex)
{
Log.Error("YouTube.UploadClipToYoutube() => Error attempting to authenticate for YouTube. Ex: " + ex);
return "";
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
Log.Info("YouTube.videosInsertRequest_ProgressChanged() => Uploading to Youtube. " + progress.BytesSent + " bytes sent.");
break;
case UploadStatus.Failed:
Log.Error("YouTube.videosInsertRequest_ProgressChanged() => An error prevented the upload from completing. Exception: " + progress.Exception);
break;
}
}
void videosInsertRequest_ResponseReceived(Google.Apis.YouTube.v3.Data.Video video)
{
Log.Info("YouTube.videosInsertRequest_ResponseReceived() => Video was successfully uploaded to YouTube. The YouTube id is " + video.Id);
UploadedVideoId = video.Id;
UploadCaptionFile(video.Id);
}
好的,我从 Java
翻译出来的东西非常快(老实说大约 15 分钟)。首先,我在您当前的代码中注意到了很多事情,但这不是 CodeReview。
The YouTubeApi v3 doesn't have much information on adding captions. All I was able to find was some old information for v2
你说得对,目前还没有(v3),但希望在不久的将来某个时候。这并不能阻止我们修改 v2,尽管这对我们有利,因为 api 非常相似...
经过测试的代码
private async Task addVideoCaption(string videoID) //pass your video id here..
{
UserCredential credential;
//you should go out and get a json file that keeps your information... You can get that from the developers console...
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.YoutubeForceSsl, YouTubeService.Scope.Youtube, YouTubeService.Scope.Youtubepartner },
"ACCOUNT NAME HERE",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
//creates the service...
var youtubeService = new Google.Apis.YouTube.v3.YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString(),
});
//create a CaptionSnippet object...
CaptionSnippet capSnippet = new CaptionSnippet();
capSnippet.Language = "en";
capSnippet.Name = videoID + "_Caption";
capSnippet.VideoId = videoID;
capSnippet.IsDraft = false;
//create new caption object
Caption caption = new Caption();
//set the completed snippet to the object now...
caption.Snippet = capSnippet;
//here we read our .srt which contains our subtitles/captions...
using (var fileStream = new FileStream("filepathhere", FileMode.Open))
{
//create the request now and insert our params...
var captionRequest = youtubeService.Captions.Insert(caption, "snippet",fileStream,"application/atom+xml");
//finally upload the request... and wait.
await captionRequest.UploadAsync();
}
}
如果您不知道文件的外观或格式,请查看示例 .srt
文件。
1
00:00:00,599 --> 00:00:03,160
>> Caption Test zaggler@ Whosebug
2
00:00:03,160 --> 00:00:05,770
>> If you're reading this it worked!
YouTube Video Proof。这是一个大约 5 秒的短片,只是为了向您展示它的工作原理和外观。并且...不,视频不是我的,抓取它进行测试 ONLY :)
祝你好运,编程愉快!
我在为上传到我公司的 YouTube 频道的视频添加字幕时遇到问题。我想在 .Net 中使用 Google 的 Youtube Api v3。我能够成功将视频上传到频道,但在尝试发送字幕时出现以下错误: "System.Net.Http.HttpRequestException: Response status code does not indicate success: 403 (Forbidden)."
据我所知,我的凭据并未禁止我上传字幕。我可以毫无问题地上传视频。
我使用此处的说明创建了刷新令牌: Youtube API single-user scenario with OAuth (uploading videos)
这是我用来创建 YouTubeService 对象的代码:
private YouTubeService GetYouTubeService()
{
string clientId = "clientId";
string clientSecret = "clientSecret";
string refreshToken = "refreshToken";
try
{
ClientSecrets secrets = new ClientSecrets()
{
ClientId = clientId,
ClientSecret = clientSecret
};
var token = new TokenResponse { RefreshToken = refreshToken };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets,
Scopes = new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload, YouTubeService.Scope.YoutubeForceSsl }
}),
"user",
token);
var service = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "TestProject"
});
service.HttpClient.Timeout = TimeSpan.FromSeconds(360);
return service;
}
catch (Exception ex)
{
Log.Error("YouTube.GetYouTubeService() => Could not get youtube service. Ex: " + ex);
return null;
}
}
这是我上传字幕文件的代码:
private void UploadCaptionFile(String videoId)
{
try
{
Caption caption = new Caption();
caption.Snippet = new CaptionSnippet();
caption.Snippet.Name = videoId + "_Caption";
caption.Snippet.Language = "en";
caption.Snippet.VideoId = videoId;
caption.Snippet.IsDraft = false;
WebRequest req = WebRequest.Create(_urlCaptionPath);
using (Stream stream = req.GetResponse().GetResponseStream())
{
CaptionsResource.InsertMediaUpload captionInsertRequest = _youtubeService.Captions.Insert(caption, "snippet", stream, "*/*");
captionInsertRequest.Sync = true;
captionInsertRequest.ProgressChanged += captionInsertRequest_ProgressChanged;
captionInsertRequest.ResponseReceived += captionInsertRequest_ResponseReceived;
IUploadProgress result = captionInsertRequest.Upload();
}
}
catch (Exception ex)
{
Log.Error("YouTube.UploadCaptionFile() => Unable to upload caption file. Ex: " + ex);
}
}
void captionInsertRequest_ResponseReceived(Caption obj)
{
Log.Info("YouTube.captionInsertRequest_ResponseReceived() => Caption ID " + obj.Id + " was successfully uploaded for this clip.");
Utility.UpdateClip(_videoClip);
}
void captionInsertRequest_ProgressChanged(IUploadProgress obj)
{
switch (obj.Status)
{
case UploadStatus.Uploading:
Console.WriteLine("{0} bytes sent.", obj.BytesSent);
break;
case UploadStatus.Failed:
Log.Error("YouTube.UploadCaptionFile() => An error prevented the upload from completing. " + obj.Exception);
break;
}
}
这几天我一直在研究这个问题,但一直没有取得任何进展。 YouTubeApi v3 没有太多关于添加字幕的信息。我所能找到的只是 v2 的一些旧信息,这需要一些 POST 调用,这些调用需要我没有的密钥。我希望能够使用 API 的内置方法添加字幕。
如果有人有处理此问题的经验,我将不胜感激你能提供的任何帮助。
编辑:
这是我将视频发送到 YouTube 的代码。
public string UploadClipToYouTube()
{
try
{
var video = new Google.Apis.YouTube.v3.Data.Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = _videoClip.Name;
video.Snippet.Description = _videoClip.Description;
video.Snippet.Tags = GenerateTags();
video.Snippet.DefaultAudioLanguage = "en";
video.Snippet.DefaultLanguage = "en";
video.Snippet.CategoryId = "22";
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "unlisted";
WebRequest req = WebRequest.Create(_videoPath);
using (Stream stream = req.GetResponse().GetResponseStream())
{
VideosResource.InsertMediaUpload insertRequest = _youtubeService.Videos.Insert(video, "snippet, status", stream, "video/*");
insertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
insertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
insertRequest.Upload();
}
return UploadedVideoId;
}
catch (Exception ex)
{
Log.Error("YouTube.UploadClipToYoutube() => Error attempting to authenticate for YouTube. Ex: " + ex);
return "";
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
Log.Info("YouTube.videosInsertRequest_ProgressChanged() => Uploading to Youtube. " + progress.BytesSent + " bytes sent.");
break;
case UploadStatus.Failed:
Log.Error("YouTube.videosInsertRequest_ProgressChanged() => An error prevented the upload from completing. Exception: " + progress.Exception);
break;
}
}
void videosInsertRequest_ResponseReceived(Google.Apis.YouTube.v3.Data.Video video)
{
Log.Info("YouTube.videosInsertRequest_ResponseReceived() => Video was successfully uploaded to YouTube. The YouTube id is " + video.Id);
UploadedVideoId = video.Id;
UploadCaptionFile(video.Id);
}
好的,我从 Java
翻译出来的东西非常快(老实说大约 15 分钟)。首先,我在您当前的代码中注意到了很多事情,但这不是 CodeReview。
The YouTubeApi v3 doesn't have much information on adding captions. All I was able to find was some old information for v2
你说得对,目前还没有(v3),但希望在不久的将来某个时候。这并不能阻止我们修改 v2,尽管这对我们有利,因为 api 非常相似...
经过测试的代码
private async Task addVideoCaption(string videoID) //pass your video id here..
{
UserCredential credential;
//you should go out and get a json file that keeps your information... You can get that from the developers console...
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.YoutubeForceSsl, YouTubeService.Scope.Youtube, YouTubeService.Scope.Youtubepartner },
"ACCOUNT NAME HERE",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
//creates the service...
var youtubeService = new Google.Apis.YouTube.v3.YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString(),
});
//create a CaptionSnippet object...
CaptionSnippet capSnippet = new CaptionSnippet();
capSnippet.Language = "en";
capSnippet.Name = videoID + "_Caption";
capSnippet.VideoId = videoID;
capSnippet.IsDraft = false;
//create new caption object
Caption caption = new Caption();
//set the completed snippet to the object now...
caption.Snippet = capSnippet;
//here we read our .srt which contains our subtitles/captions...
using (var fileStream = new FileStream("filepathhere", FileMode.Open))
{
//create the request now and insert our params...
var captionRequest = youtubeService.Captions.Insert(caption, "snippet",fileStream,"application/atom+xml");
//finally upload the request... and wait.
await captionRequest.UploadAsync();
}
}
如果您不知道文件的外观或格式,请查看示例 .srt
文件。
1
00:00:00,599 --> 00:00:03,160
>> Caption Test zaggler@ Whosebug
2
00:00:03,160 --> 00:00:05,770
>> If you're reading this it worked!
YouTube Video Proof。这是一个大约 5 秒的短片,只是为了向您展示它的工作原理和外观。并且...不,视频不是我的,抓取它进行测试 ONLY :)
祝你好运,编程愉快!