Загрузите видео на Youtube с помощью API Youtube V3 и PHP
Я пытаюсь загрузить видео на Youtube с помощью PHP. Я использую Youtube API v3, и я использую последний проверенный исходный код библиотеки API Google API PHP.
Я использую образец кода, указанный на сайте
https://code.google.com/p/google-api-php-client/ для выполнения проверки подлинности. Аутентификация проходит отлично, но когда я пытаюсь загрузить видео, я получаю Google_ServiceException
с кодом ошибки 500 и сообщением как null.
Я рассмотрел следующий вопрос, заданный ранее:
Загрузите видео на YouTube с помощью php client library v3 Но принятый ответ не описывает, как указывать загружаемые файлы.
Я нашел еще один аналогичный вопрос Загрузка файла с помощью API Youtube 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>";
}
Это что-то, что я делаю неправильно?
Ответы
Ответ 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();
}
}
Ответ 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 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 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);
Ответ 3
Я также понимаю, что это старый, , но, когда я клонировал последнюю версию php-клиента из GitHub. Я столкнулся с проблемой Google_Service_YouTube_Videos_Resource::insert()
-method.
Я бы передал массив с "data" => file_get_contents($pathToVideo)
и "mimeType" => "video/mp4"
в качестве аргумента для метода insert()
, но я все равно продолжал получать (400) BadRequest в ответ.
Отладка и чтение кода Google, который я нашел в \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);
Если я правильно помню, с версией 0.6 PHP-api аргумент uploadType не нужен. Это может относиться только к режиму прямой загрузки, а не к возобновляемой загрузке, отображаемой в ответе "Любой день".
Ответ 4
Ответ будет использовать Google_Http_MediaFileUpload через клиентские библиотеки Google PHP.
Здесь пример кода: https://github.com/youtube/api-samples/blob/master/php/resumable_upload.php