使用YouTube API创建自定义视频缩略图?

3
如何使用php youtube-api上传自定义缩略图的视频。
我尝试使用Zend框架进行youtube直接视频上传,这很有效,但我找不到任何自定义缩略图上传方法。
我尝试了以下代码:
 $parms = array('videoId => '' ,mediaUpload => '');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/upload/youtube/v3/thumbnails/set/');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parms);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: image/jpeg", 'Authorization: Bearer '.$token['access_token']));
$return = json_decode(curl_exec($ch));

error thrown
---------------
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required parameter: videoId",
    "locationType": "parameter",
    "location": "videoId"
   }
  ],
  "code": 400,
  "message": "Required parameter: videoId"
 }
}

你是否添加了必需的 videoId 参数,并且实际填写了它?错误提示显示缺少该参数。 - NoLifeKing
仅供示例,我尝试使用videoId => 'pGM3wTq0z3Y'。 - user2644621
4个回答

4
你可以使用PHP客户端库来访问数据API v3。Zend用于较早的GData API。
你可以使用此示例上传自定义缩略图。请记住,您应该拥有适当的访问权限才能上传自定义缩略图到您的频道。
// Call set_include_path() as needed to point to your client library.
require_once 'Google_Client.php';
require_once 'contrib/Google_YouTubeService.php';
session_start();

/* You can acquire an OAuth 2 ID/secret pair from the API Access tab on the Google APIs Console
 <http://code.google.com/apis/console#access>
For more information about using OAuth2 to access Google APIs, please visit:
<https://developers.google.com/accounts/docs/OAuth2>
Please ensure that you have enabled the YouTube Data API for your project. */
$OAUTH2_CLIENT_ID = 'REPLACE_ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE_ME';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
    FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

// YouTube object used to make all Data API requests.
$youtube = new Google_YoutubeService($client);

if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

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

// Check if access token successfully acquired
if ($client->getAccessToken()) {
  try{

    // REPLACE with the channel that you want to upload into
    $videoId = "VIDEO_ID";

    // REPLACE with the path to your file that you want to upload for thumbnail
    $imagePath = "/path/to/file.png";

    // Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
    // for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
    $chunkSizeBytes = 1 * 1024 * 1024;

    // Create a MediaFileUpload with resumable uploads
    $media = new Google_MediaFileUpload('image/png', null, true, $chunkSizeBytes);
    $media->setFileSize(filesize($imagePath));

    // List associated content owners to get content owner id
    $setResponse = $youtube->thumbnails->set($videoId, array('mediaUpload' => $media));

    $uploadStatus = false;

    // Read file and upload chunk by chunk
    $handle = fopen($imagePath, "rb");
    while (!$uploadStatus && !feof($handle)) {
      $chunk = fread($handle, $chunkSizeBytes);
      $uploadStatus = $media->nextChunk($setResponse, $chunk);
    }

    fclose($handle);

    $thumbnailUrl = $uploadStatus['items'][0]['default']['url'];
    $htmlBody .= "<h3>Thumbnail Uploaded</h3><ul>";
    $htmlBody .= sprintf('<li>%s (%s)</li>',
        $videoId,
        $thumbnailUrl);
    $htmlBody .= sprintf('<img src="%s">', $thumbnailUrl);
    $htmlBody .= '</ul>';


    } 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
      $state = mt_rand();
      $client->setState($state);
      $_SESSION['state'] = $state;

      $authUrl = $client->createAuthUrl();
      $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
    }
    ?>

    <!doctype html>
    <html>
    <head>
    <title>Claim Uploaded</title>
    </head>
    <body>
      <?=$htmlBody?>
    </body>
    </html>

这段代码帮助我解决了问题,而且它对我很有效。谢谢。 - Robi
Robi,你能否发布一个关于如何让它在你的机器上运行的示例吗? - Tim

0
  //CONVERT IMAGE FROM URL AND STORE
    $randomstr = generateRandomString();
    $thumbnail_url = "http://i.ytimg.com/vi/BMFLzf-DXXU/hqdefault.jpg";   
    $ch = curl_init($thumbnail_url);
    $fp = fopen('videos/'.$randomstr.'.jpg', 'wb');
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);

他想为视频设置一个新的缩略图。 - NoLifeKing
这段代码可以从指定的 YouTube URL 中获取硬盘中的缩略图图像。 - Rahul K

0

我尝试使用上述URL,但不清楚,并返回相同的错误。 - user2644621

0

videoId缺失。请先上传视频,然后使用videoId为已上传的视频创建缩略图。


我想问一下,我已经使用Zend_Gdata_YouTube将视频上传到了YouTube,但是如何通过Zend_Gdata_YouTube(或其他API)上传自定义缩略图呢? - user2644621

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