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

2022-01-19 00:00:00 youtube-api php google-api-php-client

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

I am trying to upload large videos to youtube via the latest version of the google client api (v3, latest checked out source)

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

I have it posting the videos, but the only way I can get it to work is by reading the entire video into a string, and then passing it via the data parameter.

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

I certainly do not want to read gigantic files into memory, but the api seems to offer no other way to do this. It seems to expect a string as the data parameter. Below is the code I'm using to post the video.

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

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

Is there any way to post the data in chunks, or stream the data in some way so as to avoid reading the entire file into memory?

推荐答案

以前好像不支持这个用例.这是一个适用于最新版本的 Google APIs PHP 客户端的示例(来自 https://code.google.com/p/google-api-php-client/source/checkout).

It looks like this use case wasn't supported before. Here's a sample that works with the very latest version of the Google APIs PHP client (from 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);
}

相关文章