使用PHP从S3获取视频并上传到YouTube

6

我有一些代码可以将视频文件上传到YouTube:

$yt = new Zend_Gdata_YouTube($httpClient);

// create a new VideoEntry object
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

// create a new Zend_Gdata_App_MediaFileSource object
$filesource = $yt->newMediaFileSource('file.mov');
$filesource->setContentType('video/quicktime');
// set slug header
$filesource->setSlug('file.mov');

我在S3上有视频,并想将它们上传到YouTube。我们S3帐户中的视频是公共的,所以我可以使用类似wget的命令。在运行这个脚本(shell_exec("wget ".$s3videoURL))之前,我应该运行一个将视频文件wgets并将其下载到本地的命令吗?
还是我应该尝试将MediaFileSource作为S3文件本身的URL输入?
主要是我只需要稳定性(不要求解决方案经常超时);速度和本地存储并不重要(一旦上传完成后,我可以在本地删除视频文件)。
最好的方法是什么?
谢谢!
更新:我应该提到这个脚本每次执行都会上传约5个视频到YouTube。
4个回答

9

这是一个老问题,但我认为我有一个更好的答案。

你不必将视频写入硬盘,也不能将整个文件保存在RAM中(我假设它是一个大文件)。

您可以使用PHP AWS SDK和Google Client库从S3缓冲文件并即时发送到YouTube。使用registerStreamWrapper方法将S3注册为文件系统,并使用YouTube API的可恢复上传。然后,您只需使用fread从S3读取块,并将它们发送到YouTube。这样,您甚至可以限制RAM使用。

我假设您已经从Google_Video类创建了视频对象($video代码中)。这是完整的代码。

<?php
require_once 'path/to/libraries/aws/vendor/autoload.php';
require_once 'path/to/libraries/google-client-lib/autoload.php';

use Aws\S3\S3Client;

$chunkSizeBytes = 2 * 1024 * 1024; // 2 mb
$streamName = 's3://bucketname/video.mp4';

$s3client = S3Client::factory(array(
                    'key'    => S3_ACCESS_KEY,
                    'secret' => S3_SECRET_KEY,
                    'region' => 'eu-west-1' // if you need to set.
                ));
$s3client->registerStreamWrapper();

$client = new Google_Client();
$client->setClientId(YOUTUBE_CLIENT_ID);
$client->setClientSecret(YOUTUBE_CLIENT_SECRET);
$client->setAccessToken(YOUTUBE_TOKEN);

$youtube = new Google_YoutubeService($client);
$media = new Google_MediaFileUpload('video/*', null, true, $chunkSizeBytes);

$filesize = filesize($streamName); // use it as a reguler file.
$media->setFileSize($filesize);

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

$handle = fopen($streamName, "r");
$totalReceived = 0;
$chunkBuffer = '';
while (!$uploadStatus && !feof($handle)) {
    $chunk = fread($handle, $chunkSizeBytes);
    $chunkBuffer .= $chunk;
    $chunkBufferSize = strlen($chunkBuffer);
    if($chunkBufferSize > $chunkSizeBytes) {
        $fullChunk = substr($chunkBuffer, 0, $chunkSizeBytes);
        $leapChunk = substr($chunkBuffer, $chunkSizeBytes);
        $uploadStatus = $media->nextChunk($insertResponse, $fullChunk);
        $totalSend += strlen($fullChunk);

        $chunkBuffer = $leapChunk;
        echo PHP_EOL.'Status: '.($totalReceived).' / '.$filesize.' (%'.(($totalReceived / $filesize) * 100).')'.PHP_EOL;
    }

    $totalReceived += strlen($chunk);
}

$extraChunkLen = strlen($chunkBuffer);
$uploadStatus = $media->nextChunk($insertResponse, $chunkBuffer);
$totalSend += strlen($chunkBuffer);
fclose($handle);

谢谢。你节省了我的时间 :)。 - Fawkes
以防万一有人试图简化此过程遇到问题,由于在php中从远程位置使用fread的限制,您需要将数据块附加到数据块缓冲区。来自php.net的警告: 警告:当从不是常规本地文件的任何东西(如从读取远程文件或从popen()和fsockopen()返回的流)进行读取时,读取将在可用包后停止。这意味着您应该按照下面的示例将数据收集在块中。 - bertmaclin

2
“MediaFileSource”必须是一个真实的文件。它不支持URL,因此您需要先从S3将视频复制到服务器上,然后再将其发送到YouTube。
如果您的使用量较小,则可能可以使用“shell_exec”,但出于各种原因,最好使用Zend S3 ServicecURL从S3中获取文件。

非常感谢您的回答,我将探索这些替代方案。 - SSH This

1

我不得不对@previous_developer的回答进行一些更改,以使其与Youtube Data API V3配合使用(请为他点赞,因为除了他的代码外,我找不到任何可用的代码)。

$streamName = 's3://BUCKET-NAME/VIDEO.mp4';


/**
Since I have been using Yii 2. Use the AWS 
SDK directly instead.
*/

    $aws = Yii::$app->awssdk->getAwsSdk();
    $s3client = $aws->createS3();


    $s3client->registerStreamWrapper();


    $service = new \Google_Service_YouTube($client);

    $snippet = new \Google_Service_YouTube_VideoSnippet();
    $snippet->setTitle("Test title");
    $snippet->setDescription("Test descrition");
    $snippet->setTags(array("tag1","tag2"));
    $snippet->setCategoryId("22");

    $status = new \Google_Service_YouTube_VideoStatus();
    $status->privacyStatus = "public";

    $video = new \Google_Service_YouTube_Video();
    $video->setSnippet($snippet);
    $video->setStatus($status);

    $client->setDefer(true);
    $insertResponse = $service->videos->insert("status,snippet", $video);


    $media = new MediaFileUpload(
        $client,
        $insertResponse,
        'video/*',
        null,
        true,
        false
    );

    $filesize = filesize($streamName); // use it as a reguler file.
    $media->setFileSize($filesize);


    $chunkSizeBytes = 2 * 1024 * 1024; // 2 mb

    $uploadStatus = false;

    $handle = fopen($streamName, "r");
    $totalSend = 0;
    $totalReceived = 0;
    $chunkBuffer = '';
    while (!$uploadStatus && !feof($handle)) {
        $chunk = fread($handle, $chunkSizeBytes);
        $chunkBuffer .= $chunk;
        $chunkBufferSize = strlen($chunkBuffer);
        if($chunkBufferSize > $chunkSizeBytes) {
            $fullChunk = substr($chunkBuffer, 0, $chunkSizeBytes);
            $leapChunk = substr($chunkBuffer, $chunkSizeBytes);
            $uploadStatus = $media->nextChunk($fullChunk);
            $totalSend += strlen($fullChunk);

            $chunkBuffer = $leapChunk;
            echo PHP_EOL.'Status: '.($totalReceived).' / '.$filesize.' (%'.(($totalReceived / $filesize) * 100).')'.PHP_EOL;
        }

        $totalReceived += strlen($chunk);
    }

    $extraChunkLen = strlen($chunkBuffer);
    $uploadStatus = $media->nextChunk($chunkBuffer);
    $totalSend += strlen($chunkBuffer);
    fclose($handle);



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

-1

$chunkSizeBytes = 2 * 1024 * 1024; // 2 mb

$chunkSizeBytes = 2 * 1024 * 1024; // 2兆字节

    $s3client = $this->c_aws->getS3Client();
    $s3client->registerStreamWrapper();

    try {

        $client = new \Google_Client();

        $client->setAccessType("offline");
        $client->setApprovalPrompt('force');

        $client->setClientId(GOOGLE_CLIENT_ID);
        $client->setClientSecret(GOOGLE_CLIENT_SECRET);
        $token = $client->fetchAccessTokenWithRefreshToken(GOOGLE_REFRESH_TOKEN);


        $client->setAccessToken($token);

        $youtube = new \Google_Service_YouTube($client);

        // 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's title, description, keyword tags, and
        // video category.
        $snippet = new \Google_Service_YouTube_VideoSnippet();
        $snippet->setTitle($title);
        $snippet->setDescription($summary);
        $snippet->setTags(explode(',', $keywords));

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

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

        $insertRequest = $youtube->videos->insert("status,snippet", $video);

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

        $result = $this->c_aws->getAwsFile($aws_file_path);

        $media->setFileSize($result['ContentLength']);

        $uploadStatus = false;

        // Seek to the beginning of the stream
        $result['Body']->rewind();

        // Read the body off of the underlying stream in chunks
        while (!$uploadStatus && $data = $result['Body']->read($chunkSizeBytes)) {

            $uploadStatus = $media->nextChunk($data);

        }
        $client->setDefer(false);
        if ($uploadStatus->status['uploadStatus'] == 'uploaded') {
            // Actions to perform for a successful upload
             $uploaded_video_id = $uploadStatus['id'];
            return ($uploadStatus['id']);
        }
    }catch (\Google_Service_Exception $exception){
        return '';
        print_r($exception);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接