При загрузке через YouTube API с PHP видеофайл застрял на 0%

1

Я попытался с помощью реализации, чтобы загрузить видео на мой канал из здесь:

но я застрял в очень специфической точке: после того, как я получил сообщение о том, что мое видео загружено, на странице Video Manager моей учетной записи YouTube я вижу видео, но ниже приведенное ниже сообщение статуса "0% загружено", и оно остается таким же, как это.

Кроме того, мне пришлось внести изменения в код в строке 22:

$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
file_get_contents($videoPath),
true,
$chunkSizeBytes
);

До этого, с исходным кодом, я получил сообщение "Подготовка загрузки". (также остался так).

Я знаю, что есть аналогичный вопрос здесь. После прочтения я попытался установить chunkSizeBytes ниже и даже установил его как null (в API, в src/Google/Http/MediaFileUpload.php: 88, если для него не установлено значение, оно присваивает одно).

Вот мой код для подключения к API:

<?php
header("Access-Control-Allow-Origin: *");
header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
header( 'Access-Control-Allow-Headers: *' );
session_start();
// Call set_include_path() as needed to point to your client library.
require_once 'google_api_test/src/Google/Client.php';
require_once 'google_api_test/src/Google/Service/YouTube.php';

$OAUTH2_CLIENT_ID = 'my_client_id.apps.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = 'my_client_secret';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
//redirect to the same page
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST']."/youtube-sink",
    FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

if (isset($_GET['code'])) {

    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
    //I commented this line because it kept posting the video twice
    //header('Location: ' . $redirect);

}

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
    try{
        // REPLACE this value with the path to the file you are uploading.
        $videoPath = "videos" . DIRECTORY_SEPARATOR . $videoName;

        // Create a snippet with title, description, tags and category ID
        // Create an asset resource and set its snippet metadata and type.
        // This example sets the video title, description, keyword tags, and
        // video category.
        $snippet = new Google_Service_YouTube_VideoSnippet();
        $snippet->setTitle("Test for Investing.com");
        $snippet->setDescription("This is our new video");
        $snippet->setTags(array("Investing.com", "PHP", "oauth"));

        // Numeric video category.    
        $snippet->setCategoryId("22"); //category - foreign

        $status = new Google_Service_YouTube_VideoStatus();
        $status->privacyStatus = "public"; //public,private or unlisted

        // 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 = 0.5 * 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/*',
            file_get_contents($videoPath),
            true,
            $chunkSizeBytes
        );    

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

        // If you want to make other calls after the file upload, set setDefer back to false
        $client->setDefer(false);

        $htmlBody = "<h1 class='alert alert-success text-center'>Video $videoName Uploaded</h3><ul>";
        //destroying the session to prevent users from reuploading the video if they refresh or go back
       session_destroy();
        fclose($handle);
    } catch (Google_ServiceException $e) {
        $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
            htmlspecialchars($e->getMessage()));
    } catch (Google_Exception $e) {
        $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
            htmlspecialchars($e->getMessage()));
    }

    $_SESSION['token'] = $client->getAccessToken();
} else {
    // If the user hasn't authorized the app, initiate the OAuth flow

    $authUrl = $client->createAuthUrl();
    $htmlBody = <<<END
    <div class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Authorization Required</h4>
      </div>
      <div class="modal-body">
        <p>You need to login to Youtube in order to upload that video.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <a href="$authUrl" class="btn btn-primary">Proceed</a>
      </div>
    </div>
  </div>
</div>

END;
}    
?>

<?=$htmlBody?>
  • 0
    Сколько времени вы ожидали после завершения загрузки, прежде чем проверять Video Manager. В зависимости от размера видео YouTube может занять некоторое время для обработки загруженного видео.
  • 0
    Я ждал до часа, и текст не изменился с 0% или Подготовка загрузки. Я делаю тесты с 2 МБ mp4-файла
Показать ещё 1 комментарий
Теги:
video
google-api
youtube-api

1 ответ

0
Лучший ответ

Я выяснил, в чем проблема, связанная с загрузкой. Причина ошибки была в конфигурации сервера. Мне нужно было изменить следующее:

В.htaccess следует установить

<IfModule mod_php5.c>
php_value output_buffering Off
</IfModule>

Как показано в примере загрузки YouTube YouTube API, сценарий отправляет видео в куски. Это должно быть сделано во время выполнения скрипта, а не после завершения обработки скрипта (выход буферизации = on)

Дополнительная информация о выходной буферизации

Ещё вопросы

Сообщество Overcoder
Наверх
Меню