首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Youtube API V3和PHP上传视频到Youtube

使用Youtube API V3和PHP上传视频到Youtube
EN

Stack Overflow用户
提问于 2013-01-09 21:39:17
回答 3查看 45.6K关注 0票数 23

我正在尝试上传一个视频到Youtube使用PHP。我使用的是Youtube API v3,我使用的是Google API PHP客户端库的最新检出源代码。

中给出的示例代码

执行身份验证的https://code.google.com/p/google-api-php-client/。身份验证通过得很好,但当我尝试上传视频时,我得到了Google_ServiceException,错误代码为500,消息为空。

我看了一下前面提出的问题:Upload video to youtube using php client library v3,但公认的答案并没有描述如何指定要上传的文件数据。

我发现了另一个类似的问题Uploading file with Youtube API v3 and PHP,在注释中提到categoryId是强制的,因此我尝试在代码片段中设置categoryId,但仍然给出了相同的异常。

我还参考了文档站点( https://developers.google.com/youtube/v3/docs/videos/insert )上的Python代码,但在客户端库中找不到函数next_chunk。但是我试图放一个循环(在代码片段中提到)来重试得到错误代码500,但在所有10次迭代中,我都得到了相同的错误。

以下是我正在尝试的代码片段:

代码语言:javascript
复制
$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>";
}

是不是我做错了什么?

EN

回答 3

Stack Overflow用户

发布于 2013-01-14 04:12:31

我能够使用下面的代码让上传工作起来:

代码语言:javascript
复制
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();
    }
}
票数 8
EN

Stack Overflow用户

发布于 2014-05-02 10:04:37

我知道这很古老,但这是文档中的答案:

代码语言:javascript
复制
    // 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);
票数 4
EN

Stack Overflow用户

发布于 2014-10-18 04:16:00

答案是通过Google PHP client libraries使用Google_Http_MediaFileUpload。

下面是示例代码:https://github.com/youtube/api-samples/blob/master/php/resumable_upload.php

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14236502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档