2013-01-09 13 views
20

Ich versuche ein Video mit PHP auf Youtube hochzuladen. Ich verwende Youtube API v3 und verwende den aktuellsten ausgecheckten Quellcode der Google API PHP Client Bibliothek.
Ich verwende den Beispielcode
https://code.google.com/p/google-api-php-client/, um die Authentifizierung durchzuführen. Die Authentifizierung läuft gut, aber wenn ich versuche, ein Video hochzuladen, bekomme ich Google_ServiceException mit Fehlercode 500 und Nachricht als null.Video mit Youtube API V3 und PHP auf Youtube hochladen

Ich habe mir die folgende Frage angesehen früher: Upload video to youtube using php client library v3 Aber die akzeptierte Antwort beschreibt nicht, wie Dateidaten zum Hochladen angegeben werden.
Ich fand eine andere ähnliche Frage Uploading file with Youtube API v3 and PHP, wo in dem Kommentar erwähnt wird, dass categoryId obligatorisch ist, daher habe ich versucht, die categoryId im Schnipsel zu setzen, aber es gibt immer noch die gleiche Ausnahme.

Ich habe auch auf den Python-Code auf der Dokumentations-Website (https://developers.google.com/youtube/v3/docs/videos/insert) verwiesen, aber ich konnte die Funktion next_chunk in der Client-Bibliothek nicht finden. Aber ich habe versucht, eine Schleife (im Code-Snippet erwähnt) zu setzen, um zu versuchen, Fehlercode 500 zu bekommen, aber in allen 10 Iterationen bekomme ich den gleichen Fehler.

Es folgt der Code-Schnipsel Ich versuche:

$youTubeService = new Google_YoutubeService($client); 
if ($client->getAccessToken()) { 
    print "Successfully authenticated"; 
    $snippet = new Google_VideoSnippet(); 
    $snippet->setTitle = "My Demo title"; 
    $snippet->setDescription = "My Demo descrition"; 
    $snippet->setTags = array("tag1","tag2"); 
    $snippet->setCategoryId(23); // this was added later after refering to another question on stackoverflow 

    $status = new Google_VideoStatus(); 
    $status->privacyStatus = "private"; 

    $video = new Google_Video(); 
    $video->setSnippet($snippet); 
    $video->setStatus($status); 

    $data = file_get_contents("video.mp4"); // This file is present in the same directory as the code 
    $mediaUpload = new Google_MediaFileUpload("video/mp4",$data); 
    $error = true; 
    $i = 0; 

    // I added this loop because on the sample python code on the documentation page 
    // mentions we should retry if we get error codes 500,502,503,504 
    $retryErrorCodes = array(500, 502, 503, 504); 
    while($i < 10 && $error) { 
     try{ 
      $ret = $youTubeService->videos->insert("status,snippet", 
                $video, 
                array("data" => $data)); 

      // tried the following as well, but even this returns error code 500, 
      // $ret = $youTubeService->videos->insert("status,snippet", 
      //          $video, 
      //          array("mediaUpload" => $mediaUpload); 
      $error = false; 
     } catch(Google_ServiceException $e) { 
      print "Caught Google service Exception ".$e->getCode() 
        . " message is ".$e->getMessage(); 
      if(!in_array($e->getCode(), $retryErrorCodes)){ 
       break; 
      } 
      $i++; 
     } 
    } 
    print "Return value is ".print_r($ret,true); 

    // We're not done yet. Remember to update the cached access token. 
    // Remember to replace $_SESSION with a real database or memcached. 
    $_SESSION['token'] = $client->getAccessToken(); 
} else { 
    $authUrl = $client->createAuthUrl(); 
    print "<a href='$authUrl'>Connect Me!</a>"; 
} 

Ist es etwas, was ich falsch mache?

+0

Können Sie einen Stack-Trace schreiben? Ich vermute, das Problem ist das: http://code.google.com/p/gdata-issues/issues/detail?id=3961 –

+0

Ich hatte dieses Problem auch gesehen.Wenn resumeable als true gesetzt ist, bekomme ich diese Ausnahme "Uncaught exception 'Google_Exception' mit der Nachricht 'Der fortsetzbare Upload konnte nicht gestartet werden" mit dem Fehlercode 400, ansonsten gibt es immer den Fehlercode 500 mit der Nachricht null. – jayendrap

Antwort

8

konnte ich den Upload bekommen Sie den folgenden Code arbeiten mit:

if($client->getAccessToken()) { 
    $snippet = new Google_VideoSnippet(); 
    $snippet->setTitle("Test title"); 
    $snippet->setDescription("Test descrition"); 
    $snippet->setTags(array("tag1","tag2")); 
    $snippet->setCategoryId("22"); 

    $status = new Google_VideoStatus(); 
    $status->privacyStatus = "private"; 

    $video = new Google_Video(); 
    $video->setSnippet($snippet); 
    $video->setStatus($status); 

    $error = true; 
    $i = 0; 

    try { 
     $obj = $youTubeService->videos->insert("status,snippet", $video, 
             array("data"=>file_get_contents("video.mp4"), 
             "mimeType" => "video/mp4")); 
    } catch(Google_ServiceException $e) { 
     print "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage(). " <br>"; 
     print "Stack trace is ".$e->getTraceAsString(); 
    } 
} 
+0

Ich verwende Ihren Code, aber er lädt die Videos nicht hoch, sollte ich etwas zum Code hinzufügen? Ich habe Echo "obj:" hinzugefügt. $ Obj; aber es zeigt nichts. –

+1

Gibt es eine Ausnahme, die ausgelöst wird? – jayendrap

+1

danke für deine Antwort, ich könnte das Problem lösen, es funktioniert, aber ich kann keine großen Dateien hochladen, ich versuche, wiederaufladbare Upload zu verwenden, aber funktioniert nicht, haben Sie eine Idee? –

3

Ich weiß, das alt ist, aber hier ist die Antwort aus der Dokumentation:

// REPLACE this value with the path to the file you are uploading. 
    $videoPath = "/path/to/file.mp4"; 

    $snippet = new Google_Service_YouTube_VideoSnippet(); 
    $snippet->setTitle("Test title"); 
    $snippet->setDescription("Test description"); 
    $snippet->setTags(array("tag1", "tag2")); 

    // Numeric video category. See 
    // https://developers.google.com/youtube/v3/docs/videoCategories/list 
    $snippet->setCategoryId("22"); 

    // Set the video's status to "public". Valid statuses are "public", 
    // "private" and "unlisted". 
    $status = new Google_Service_YouTube_VideoStatus(); 
    $status->privacyStatus = "public"; 

    // Associate the snippet and status objects with a new video resource. 
    $video = new Google_Service_YouTube_Video(); 
    $video->setSnippet($snippet); 
    $video->setStatus($status); 

    // Specify the size of each chunk of data, in bytes. Set a higher value for 
    // reliable connection as fewer chunks lead to faster uploads. Set a lower 
    // value for better recovery on less reliable connections. 
    $chunkSizeBytes = 1 * 1024 * 1024; 

    // Setting the defer flag to true tells the client to return a request which can be called 
    // with ->execute(); instead of making the API call immediately. 
    $client->setDefer(true); 

    // Create a request for the API's videos.insert method to create and upload the video. 
    $insertRequest = $youtube->videos->insert("status,snippet", $video); 

    // Create a MediaFileUpload object for resumable uploads. 
    $media = new Google_Http_MediaFileUpload(
     $client, 
     $insertRequest, 
     'video/*', 
     null, 
     true, 
     $chunkSizeBytes 
    ); 
    $media->setFileSize(filesize($videoPath)); 


    // Read the media file and upload it chunk by chunk. 
    $status = false; 
    $handle = fopen($videoPath, "rb"); 
    while (!$status && !feof($handle)) { 
     $chunk = fread($handle, $chunkSizeBytes); 
     $status = $media->nextChunk($chunk); 
    } 

    fclose($handle); 

    // If you want to make other calls after the file upload, set setDefer back to false 
    $client->setDefer(false); 
+0

Dies ist genau dieses Beispiel https://github.com/youtube /api-samples/blob/master/php/resumable_upload.php falls jemand diese Antwort gefunden hat und neugierig ist. – Link14

2

ich auch erkennen, das ist alt, aber als ich die neueste Version von PHP-Client von GitHub geklont habe, lief ich in Schwierigkeiten mit Google_Service_YouTube_Videos_Resource::insert() -Methode.

Ich würde ein Array mit "data" => file_get_contents($pathToVideo) und "mimeType" => "video/mp4" eingestellt als Argument für die insert() -Methode, aber ich immer noch passieren (400) BadRequest im Gegenzug zu bekommen.

Debuggen und das Lesen durch den Google-Code fand ich in \Google\Service\Resource.php gab es einen Scheck (auf den Leitungen 179-180) gegen eine Reihe Schlüssel "uploadType", der das Objekt Google_Http_MediaFielUpload initiieren würde.

$part = 'status,snippet'; 
$optParams = array(
    "data" => file_get_contents($filename), 
    "uploadType" => "media", // This was needed in my case 
    "mimeType" => "video/mp4", 
); 
$response = $youtube->videos->insert($part, $video, $optParams); 

Wenn ich mich richtig erinnere, mit der Version 0.6 des PHP-api das uploadType Argument wurde nicht benötigt. Dies gilt möglicherweise nur für den direkten Upload-Stil und nicht den wiederaufsetzbaren Upload, der in Any Day's Antwort angezeigt wird.

Verwandte Themen