2016-04-07 36 views
0

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

私の知る限り、私の資格情報はキャプションのアップロードを禁止しません。私は問題なくビデオをアップロードすることができます。

私はここの手順を使用してリフレッシュトークンを作成しました: 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); 
    } 
+0

ごくわずかです。認証に関して、あなたはアップロードと同じプロセスを使用していますか? * 403禁止されているエラー(これは明白ですが、私も考える価値があると思います)では、あなたのキャプションデータは[constraints](https://developers.google.com/youtube/v3/docs/captions/insert)に準拠していますか? #要求)。また、私はこれを見ました[同様の投稿](http://stackoverflow.com/questions/31823160/uploading-captions-using-youtube-api-v3-dotnet-c-null-error-challenging)、違いは彼が受け取ったエラー、あなたは自分のコードをチェックしようとしましたか? :) –

+0

ビデオのアップロードプロセスは、キャプションのアップロードプロセスとほぼ同じです。元の投稿を私が使っているビデオアップロードプロセスで更新します。私は、資格情報を作成する際にスコープの1つとして「YouTubeService.Scope.YoutubeForceSsl」を持っているので、すべてが制約に準拠する必要があります。私はそのようなポストを見てきました。実際には、代理人の1人は元の同僚で、彼が出発する前にこのプロジェクトに取り組んでいて、私は引き継ぎました。残念ながら、彼が投稿したコードは動作しません。 – Chelsea

+1

@Chelseaこれは 'v3'ではありません。バージョン3は、Oauthのた​​めに 'GoogleWebAuthorizationBroker'と' FileDataStore'を使用しています...また、アプリケーションのロックを防ぐ 'await'と' async'操作も使用します。新しいバージョンを古いバージョンと混在させる可能性はありますか?また、私はあなたの要求のためのユーザー名を提供していないと思われる、これはエラーの可能性がありますか、セキュリティの理由からこれを残して... – Codexer

答えて

1

さてさて、私は私がJavaから翻訳あなたのために本当に速い何か(正直に約15分)を手早く。最初に、あなたの現在のコードで気づいたことがいくつかありますが、これはCodeReviewではありません。

YouTubeApi v3ではキャプションの追加に関する情報がほとんどありません。私は見つけることができたすべてがうまくいけば、いつか近い将来、それはこの時間(V3)でない、あなたがこのことについて正しいV2

のためのいくつかの古い情報でした。 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 [email protected] StackOverflow 

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

YouTube Video Proof。それは、あなたがそれが動作しているように見えるだけで、それがどのように見えるかについて約5秒の短いクリップです。そして...ノービデオは、私のものではありませんONLY :)

幸運と幸せなプログラミングをテストするためにそれをつかみました!

+0

ありがとうございました!私のプログラムは今働きます! – Chelsea

+0

ようこそ、私は助けてうれしい!資格= GoogleWebAuthorizationBroker.AuthorizeAsyncを待つ( GoogleClientSecrets.Load(ストリーム).Secrets、 新しい[] {YouTubeService.Scope.YoutubeForceSsl、YouTubeService.Scope.Youtube、YouTubeService.Scope.Youtubepartner}、 「アカウントNAME HERE:このセクション – Codexer

+0

"、 CancellationToken.None、 新しいFileDataStore(this.GetType()。ToString()) ); –

関連する問題