通过google php client api v3将大型视频发布到youtube

时间:2013-01-22 18:27:24

标签: php youtube-api google-api-php-client

我正在尝试通过最新版本的google客户端API(v3,最新检出来源)将大型视频上传到youtube

我发布了视频,但我能让它工作的唯一方法是将整个视频读成一个字符串,然后通过data参数传递它。

我当然不想将巨大的文件读入内存,但api似乎没有提供其他方法来做到这一点。它似乎期望一个字符串作为data参数。以下是我用来发布视频的代码。

$snippet = new Google_VideoSnippet();
$snippet->setTitle("Test title2");
$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);

$videoData = file_get_contents($pathToMyFile);
$youtubeService->videos->insert("status,snippet", $video, array("data" => $videoData, "mimeType" => "video/mp4"));

有没有办法以块的形式发布数据,或以某种方式流式传输数据,以避免将整个文件读入内存?

1 个答案:

答案 0 :(得分:4)

之前看起来不支持此用例。以下是适用于最新版本的Google API PHP客户端的示例(来自https://code.google.com/p/google-api-php-client/source/checkout)。

if ($client->getAccessToken()) {
  $videoPath = "path/to/foo.mp4";
  $snippet = new Google_VideoSnippet();
  $snippet->setTitle("Test title2");
  $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);

  $chunkSizeBytes = 1 * 1024 * 1024;
  $media = new Google_MediaFileUpload('video/mp4', null, true, $chunkSizeBytes);
  $media->setFileSize(filesize($videoPath));

  $result = $youtube->videos->insert("status,snippet", $video,
      array('mediaUpload' => $media));

  $status = false;
  $handle = fopen($videoPath, "rb");
  while (!$status && !feof($handle)) {
    $chunk = fread($handle, $chunkSizeBytes);
    $uploadStatus = $media->nextChunk($result, $chunk);
  }

  fclose($handle);
}