使用YouTube API V3和PHP视频上传至YouTube(Upload video to Y

2019-07-18 01:21发布

我想上传使用PHP的Youtube视频。 我使用的Youtube API v3和我使用谷歌API PHP客户端库的最新签出的源代码。
我使用给出的示例代码
https://code.google.com/p/google-api-php-client/进行认证。 该认证经过精细,但当我尝试上传的视频,我得到Google_ServiceException ,错误代码500和消息为空。

我看了一下以下问题刚才问: 上传视频的YouTube使用PHP客户端库V3到 ,但接受的答案没有描述如何指定文件数据上传。
我发现了另一个类似的问题与YouTube API v3和PHP上传文件 ,凡在评论中提到,的categoryId是强制性的,因此我试图在段设置的categoryId但仍给出了同样的异常。

我还提到了Python代码的文档网站( https://developers.google.com/youtube/v3/docs/videos/insert ),但我找不到客户端库功能next_chunk。 但我试图把一个循环(代码段提到的)重试对收到错误代码500,但在所有的10次迭代,我得到了同样的错误。

以下是代码片段我想:

$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>";
}

难道我做错了什么吗?

Answer 1:

我能得到上传使用下面的代码工作:

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();
    }
}


Answer 2:

我意识到这是旧的,但这里的答案关闭文档:

    // 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);


Answer 3:

我也知道这是老了, 我克隆了最新版的PHP客户端的从GitHub我跑与麻烦Google_Service_YouTube_Videos_Resource::insert() -方法。

我将通过以与阵列"data" => file_get_contents($pathToVideo)"mimeType" => "video/mp4"设置为用于一个参数insert() -方法,但我仍然一直得到(400)错误请求回报。

调试并通过谷歌的代码阅读中,我发现在\Google\Service\Resource.php有一个检查(线179-180)对一个数组的键"uploadType" ,将启动Google_Http_MediaFielUpload对象。

$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);

如果我没有记错,与PHP-API 0.6版本不需要uploadType说法。 这可能仅适用于任何一天的回答显示了直接上传的风格,而不是继续上传。



Answer 4:

答案是通过使用Google_Http_MediaFileUpload 谷歌PHP客户端库 。

这里的示例代码: https://github.com/youtube/api-samples/blob/master/php/resumable_upload.php



文章来源: Upload video to Youtube using Youtube API V3 and PHP