如何在插入时向 youtube 视频添加缩略图

How to add thumbnail to youtube video upon insert

问题:

如何在插入 YouTube 视频时正确添加缩略图?

我尝试过的(一步一步):

在google-api-php-客户端中存在一个名为

的服务
$snippet = new \Google_Service_YouTube_VideoSnippet();

通过这个我可以像这样设置缩略图:

$snippet->setThumbnails($thumbnail_details);

但是它要求实例类型的参数:

$thumbnail_details = new \Google_Service_YouTube_ThumbnailDetails();

我认为这是 class 我可以设置缩略图的地方 URL,但事实并非如此。这个 class 有一个名为 "setDefault" 的方法,我可以在其中放入另一个类型实例的参数:

$thumbnail_service = new \Google_Service_YouTube_Thumbnail();

其中有一个方法叫做:

$thumbnail_service->setUrl($thumbnail_url);

这就是我所做的。 url 工作正常(例如:here)。即使在设置 url 并上传视频后,设置了错误的缩略图。 (我假设如果没有缩略图,它会选择视频中的随机帧作为缩略图)

相关代码:

    $thumbnail_service = new \Google_Service_YouTube_Thumbnail();
    $thumbnail_details = new \Google_Service_YouTube_ThumbnailDetails();

    $thumbnail_service->setUrl($thumbnail_url);
    $thumbnail_details->setDefault($thumbnail_service);

    $snippet = new \Google_Service_YouTube_VideoSnippet();
    /*
      Other video info added to snippet
    */
    $snippet->setThumbnails($thumbnail_details);

我在上传 YouTube 视频时找不到如何上传缩略图。每次上传视频后,我会从上传后返回的响应中获取 youtube 视频 ID,并准备第二个请求将缩略图上传到该特定视频。

private function UploadThumbnail($video_id, $url){

    $this->client->setDefer(true);
    $thumb = $this->youtube->thumbnails->set($video_id);
    $media = new \Google_Http_MediaFileUpload(
        $this->client,
        $thumb,
        'image/png',
        null,
        true,
        $this->chunkSizeBytes
    );

    $filesize = DataRetrievalService::remote_filesize($url);

    $this->MediaUpload($media, $url, $filesize);
}
private function MediaUpload($media, $path, $filesize = null){
    if(is_null($filesize)){
        $filesize = filesize($path);
    }
    $media->setFileSize($filesize);

    $status = false;
    $handle = fopen($path, "rb");

    while(!$status && !feof($handle)){
        $chunk = fread($handle, $this->chunkSizeBytes);

        $status = $media->nextChunk($chunk);
    }
    fclose($handle);
    $this->client->setDefer(false);
    return $status;
}

如果对我编写的代码有任何具体问题,请发表评论。我会详细解释的。

使用此代码解决问题

$video_id=$v->getId();
$url="image.jpg";
    $client->setDefer(true);
    $thumb = $youtube->thumbnails->set($video_id);
    $media = new \Google_Http_MediaFileUpload(
        $client,
        $thumb,
        'image/png',
        null,
        true,
        $chunkSizeBytes
    );

    $media->setFileSize(filesize($url));
    // Read the media file and upload it chunk by chunk.
    $status = false;
    $handle = fopen($url, "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);