php - 如何在插入时向 YouTube 视频添加缩略图

标签 php video youtube google-api-php-client symfony

问题:

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

我尝试过的内容(逐步):

在 google-api-php-client 中存在一个名为的服务

$snippet = new \Google_Service_YouTube_VideoSnippet();

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

$snippet->setThumbnails($thumbnail_details);

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

$thumbnail_details = new \Google_Service_YouTube_ThumbnailDetails();

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

$thumbnail_service = new \Google_Service_YouTube_Thumbnail();

其中有一个方法称为:

$thumbnail_service->setUrl($thumbnail_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;
}

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

关于php - 如何在插入时向 YouTube 视频添加缩略图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35648345/

相关文章:

javascript - YouTube 网格图库 : How can I get the player to appear in a popup?

web-applications - Youtube iframe api没有打开ios native 视频播放器-webapp

php - 创建/拆分字符串到标签的最佳方法

wowza 服务器上的视频流延迟,ffmpeg 的质量非常低

php - 如何复制客户地址?

video - 我不能用 ffplay 播放 HEVC 编码的 Flv 格式的视频文件

ios - 是否可以用不同的视频播放 2 个不同的 avplayer?

youtube - Youtube API v3 data.search返回相同的值

PHP:来自正态分布的随机数

PHP - 正则表达式 - 匹配长度