0

会社の YouTube チャンネルにアップロードされたビデオにキャプションを追加する際に問題が発生しています。.NetでGoogleのYoutube Api v3でやりたいです。ビデオをチャネルに正常にアップロードできますが、キャプションを送信しようとすると次のエラーが発生します:「System.Net.Http.HttpRequestException: 応答ステータス コードは成功を示しません: 403 (禁止)」。

私が知る限り、資格情報ではキャプションのアップロードが禁止されていません。問題なく動画をアップロードできます。

ここの手順を使用して更新トークンを作成しました: OAuth を使用した Youtube API シングルユーザー シナリオ (動画のアップロード)

これは、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);
    }
4

1 に答える 1

1

よし、私は から翻訳したものをあなたのために非常に手短に (正直なところ約 15 分) 作成しましたJava。まず、現在のコードで気付いた点がいくつかありますが、これはCodeReviewではありません。

YouTubeApi v3 には、キャプションの追加に関する情報があまりありません。私が見つけることができたのは、v2の古い情報だけでした

あなたはこれについて正しいです、それは現時点ではありませんが(v3)、うまくいけば近い将来にいつか。これは、API が非常に似ているため、v2 を変更することを妨げるものではありません...

試してテストしたコード

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@ StackOverflow

2
00:00:03,160 --> 00:00:05,770
>> If you're reading this it worked!

YouTube ビデオの証拠。これは約 5 秒の短いクリップで、機能と外観を示しています。そして... いいえ、ビデオは私のものではありません。テスト用にのみ取得しました:)

幸運と幸せなプログラミング!

于 2016-04-09T00:55:49.597 に答える