2010-06-08 12 views
5

Estoy usando .NET para crear una aplicación de carga de videos. Aunque es que se comunica con YouTube y carga el archivo, el proceso de falla. YouTube me da el mensaje de error "Falló la carga (no se puede convertir el archivo de video)". Se supone que esto significa que "el vídeo está en un formato que nuestros convertidores no reconocen ..."youtube - falla de carga de video - no se puede convertir el archivo - ¿la codificación del video es incorrecta?

he hecho intentos con dos videos diferentes, los cuales suben y el proceso bien cuando lo hago manualmente . Así que sospecho que mi código es a) que no codifica el video correctamente y/o b) que no envía mi solicitud de API correctamente.

A continuación se muestra cómo estoy construyendo mi solicitud de API PUT y codifica la vídeo:

alguna sugerencia sobre lo que podría ser sería apreciado el error.

Gracias

P.S. No estoy usando la biblioteca del cliente porque mi aplicación usará la característica de carga reanudable. Por lo tanto, estoy construyendo manualmente mis solicitudes API .

Documentación: http://code.google.com/intl/ja/apis/youtube/2.0/developers_guide_protocol_resumable_uploads.html#Uploading_the_Video_File

Código:

  // new PUT request for sending video 
      WebRequest putRequest = WebRequest.Create(uploadURL); 

      // set properties 
      putRequest.Method = "PUT"; 
      putRequest.ContentType = getMIME(file); //the MIME type of the uploaded video file 

      //encode video 
      byte[] videoInBytes = encodeVideo(file); 

    public static byte[] encodeVideo(string video) 
    { 
     try 
     { 
      byte[] fileInBytes = File.ReadAllBytes(video); 
      Console.WriteLine("\nSize of byte array containing " + video + ": " + fileInBytes.Length); 
      return fileInBytes; 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("\nException: " + e.Message + "\nReturning an empty byte array"); 
      byte [] empty = new byte[0]; 
      return empty; 
     } 
    }//encodeVideo 

      //encode custom headers in a byte array 
      byte[] PUTbytes = encode(putRequest.Headers.ToString()); 

      public static byte[] encode(string headers) 
      {    
       ASCIIEncoding encoding = new ASCIIEncoding(); 
       byte[] bytes = encoding.GetBytes(headers); 
       return bytes; 
      }//encode 

      //entire request contains headers + binary video data 
      putRequest.ContentLength = PUTbytes.Length + videoInBytes.Length; 

      //send request - correct? 
      sendRequest(putRequest, PUTbytes); 
      sendRequest(putRequest, videoInBytes); 

    public static void sendRequest(WebRequest request, byte[] encoding) 
    { 
     Stream stream = request.GetRequestStream(); // The GetRequestStream method returns a stream to use to send data for the HttpWebRequest. 

     try 
     { 
      stream.Write(encoding, 0, encoding.Length); 

     } 
     catch (Exception e) 
     { 
      Console.WriteLine("\nException writing stream: " + e.Message); 
     } 
    }//sendRequest 
+0

por favor no repita las etiquetas como ".NET" en el título. Déjalos en las etiquetas a las que pertenecen. –

Respuesta

0

No sé qué formato YouTube está buscando, pero si se trata de un formato que debe ser reconocible en el sistema Windows, sugiero que guarde su video convertido a un archivo en el disco, luego intente abrirlo.

0

La solicitud de envío está hecha en 2 partes ... Envía el encabezado, incluido el tamaño del video como lo ha hecho ... YouTube responde con una url y envía el video a esa url .. Parece Está intentando enviar todo en una solicitud. Algo así como esto.

Try 
     Try 
      _request = CType(WebRequest.Create(_requestUrl), HttpWebRequest) 

      With _request 
       .ContentType = "application/atom+xml; charset=UTF-8" 
       .ContentLength = _postBytes.Length 
       .Method = "POST" 
       .Headers.Add("Authorization", String.Format("GoogleLogin auth={0}", MasterAccessToken.ClientLoginToken)) 
       .Headers.Add("GData-Version", "2") 
       .Headers.Add("X-GData-Key", String.Format("key={0}", YouTube.Constants.Security.DEVELOPERKEY)) 
       .Headers.Add("Slug", filename) 
      End With 

      _writeStream = _request.GetRequestStream 
      With _writeStream 
       .Write(_postBytes, 0, _postBytes.Length) 
      End With 

      Using _response = CType(_request.GetResponse, HttpWebResponse) 
       With _response 
        If .StatusCode = HttpStatusCode.OK OrElse .StatusCode = HttpStatusCode.Created Then 
         _ans = _response.Headers("Location") 
        Else 
         Throw New WebException("Cannot get ClientLogin upload location", Nothing, WebExceptionStatus.ProtocolError, _response) 
        End If 
       End With 
      End Using 

     Catch ex As Exception 

     Finally 
      If _writeStream IsNot Nothing Then 
       _writeStream.Close() 
      End If 

     End Try 

     _videoUploadLocation = _ans 

     'Got the upload location..... now get the file 
     Dim _file As FileInfo = New FileInfo(filename) 
     Dim _fileLength As Integer 

     Using _fileStream As System.IO.FileStream = _file.OpenRead 
      _fileLength = CType(_fileStream.Length, Integer) 

      If _fileLength = 0 Then 
       Throw New FileLoadException("File appears to be of zero length in UploadVideoFromFileClientLogin:", filename) 
      End If 

      'create the webrequest 
      _request = CType(WebRequest.Create(_videoUploadLocation), HttpWebRequest) 

      'No authentication headers needed.. 
      With _request 
       .Timeout = 6000000  'Timeout for this request changed to 10 minutes 
       .ReadWriteTimeout = 6000000 
       .KeepAlive = True 
       .ContentType = "application/octet-stream" 
       .ContentLength = _fileLength 
       .Method = "POST" 
      End With 

      'and get the stream 
      _writeStream = _request.GetRequestStream 

      'And send it over the net 
      m_StreamUtils.CancelRequest = False 
      m_StreamUtils.SendStreamToStream(_fileStream, _writeStream, AddressOf UploadPogressChanged) 
      m_CancelRequest = m_StreamUtils.CancelRequest 
     End Using 

     If Not (m_CancelRequest) Then 

      Using _response = CType(_request.GetResponse, HttpWebResponse) 
       With _response 
        If .StatusCode = HttpStatusCode.Created Then 
         _ans = _response.ResponseUri.AbsoluteUri 
        Else 
         Throw New WebException("Cannot get ClientLogin upload location", Nothing, WebExceptionStatus.ProtocolError, _response) 
        End If 
       End With 
      End Using 
     Else 
      _ans = String.Empty 

     End If 

     If _writeStream IsNot Nothing Then 
      _writeStream.Close() 
     End If 
Cuestiones relacionadas