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

时间:2012-04-10 22:01:21

标签: php upload youtube amazon-s3

我有一些代码可以将视频文件上传到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))之前,我应该运行一个命令来获取视频文件并将其下载到本地吗?

或者我应该尝试输入MediaFileSource作为S3文件本身的URL吗?

主要是,我只需要稳定性(不是经常超时的解决方案);速度和本地存储并不重要(我可以在上传后在本地删除视频文件)。

最好的方法是什么?

谢谢!

更新:我应该提一下,这个剧本每次执行时会将大约5个视频上传到YouTube。

4 个答案:

答案 0 :(得分:7)

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

您不必将视频写入硬盘驱动器,而且您无法将整个视频保存在RAM中(我认为它是一个大文件)。

您可以使用PHP AWS SDK和Google Client库缓存来自S3的文件,并将其即时发送到YouTube。使用registerStreamWrapper方法将S3注册为文件系统,并使用来自YouTube API的可恢复上传。然后,您所要做的就是从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);

答案 1 :(得分:2)

“MediaFileSource”必须是真实文件。它不会占用网址,因此您需要先将视频从S3复制到服务器,然后再将其发送到YouTube。

如果您的使用很少,您可以使用“shell_exec”,但由于各种原因,最好使用Zend S3 ServicecURL从S3中提取文件。

答案 2 :(得分:0)

我必须对@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);

答案 3 :(得分:-1)

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

    $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-&gt; setCategoryId(&#34; 22&#34;);

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