2014-02-04 1 views
5

Я использую .net nuget (Google.Apis.YouTube.v3) от Google для вызовов API. Все работает до сих пор (получение плейлистов, видеоинформации и т. Д.). Но когда я пытаюсь загрузить видео, он заканчивается в течение нескольких секунд, и ничего не происходит. upload_ResponseReceived никогда не вызывается, и upload_ProgressChanged только дважды вызывается со следующим выходом: 1) Bytes sent: 0, Status: Starting, Exception: через некоторое время 2) Bytes sent: 0, Status: Failed, Exception: System.Threading.Tasks.TaskCanceledException: A task was canceled.YouTube-API загружает файлы без ошибок (C#)

Пример кода:

using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.IO; 
using System.Linq; 
using System.Reflection; 
using System.Text; 
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 UploadTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      UserCredential credential; 
      using (FileStream stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) 
      { 
       credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets, 
        new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload }, 
        "user", 
        CancellationToken.None, 
        new FileDataStore("YouTube.Auth.Store")).Result; 
      } 
      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 = @"E:\video.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; 
       videosInsertRequest.Upload(); 
      } 
      Console.ReadLine(); 
     } 

     private static void videosInsertRequest_ResponseReceived(Video obj) 
     { 
      Debug.WriteLine("Video has been uploaded! ID: {0}",obj.Id); 
     } 

     private static void videosInsertRequest_ProgressChanged(IUploadProgress obj) 
     { 
      Debug.WriteLine("Bytes sent: {0}, Status: {1}, Exception: {2}", obj.BytesSent, obj.Status, obj.Exception); 
     } 
    } 
} 

StackTrace:

System.AggregateException was unhandled. 
    HResult=-2146233088 
    Message=One or more errors occurred. 
    Source=mscorlib 
    StackTrace: 
     at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) 
     at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) 
     at System.Threading.Tasks.Task`1.get_Result() 
     at Google.Apis.Upload.ResumableUpload`1.Upload() in c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\output\default\Src\GoogleApis\Apis\[Media]\Upload\ResumableUpload.cs:line 351 
     at UploadTest.Program.<>c__DisplayClass2.<Main>b__1() in e:\Development\UploadTest\Program.cs:line 52 
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Threading.ThreadHelper.ThreadStart() 
    InnerException: System.Threading.Tasks.TaskCanceledException 
     HResult=-2146233029 
     Message=A task was canceled. 
     InnerException: 

Любая идея, что я могу делать неправильно?

+0

Какого Возвращаемый объект (IUploadProgress) содержит? Какие свойства исключения и состояния содержатся? – peleyal

+0

Байты отправлены: 0, Статус: Сбой, Исключение: Ссылка на объект не установлена ​​в экземпляр объекта. – Science

+0

До этого я получаю отправленные байты: 0, Статус: Начиная с – Science

ответ

5

Хорошо, я думаю, что у вас есть проблемы с подключением, все, что вам нужно сделать, это изменение размера куска до меньшего размера, так что ваш код должен выглядеть примерно так:

const int KB = 0x400; 
var minimumChunkSize = 256 * KB; 

var videosInsertRequest = youtubeService.Videos.Insert(video, 
    "snippet,status", fileStream, "video/*"); 
videosInsertRequest.ProgressChanged += 
    videosInsertRequest_ProgressChanged; 
videosInsertRequest.ResponseReceived += 
    videosInsertRequest_ResponseReceived; 
// The default chunk size is 10MB, here will use 1MB. 
videosInsertRequest.ChunkSize = minimumChunkSize * 4; 
videosInsertRequest.Upload(); 
+0

Спасибо, что работает сейчас! – Science

+0

Спасибо вам большое! Проблема уменьшает размер блока. – hubert17