我可以从 YouTube API3.0 获取视频的持续时间,即使它是搜索结果吗?

Can I get duration of the videos from YouTuve API3.0 even if it's search result?

我知道如果直接获取特定视频它可以获得持续时间。
如果是搜索结果呢?

我很确定它为我们提供了视频的标题、唯一 ID 和发布日期。

在我下面的代码中,除非我将 contentDetails 放入第 4 行,否则不会发生任何错误。

part section 超过2个时好像会报错
如果我将它保留为 :part => 'snippet',,一切正常。
但是,我必须添加 contentDetails 才能获得有关 Youtube 上视频持续时间的信息。

如何实现?

videos_controller.rb

@search_response = client.execute!(
  :api_method => youtube.search.list,
  :parameters => {
    :part => 'snippet, contentDetails',
    :q => 'cats',
    :maxResults => 20,
    :order => 'date',
    :pageToken => pageToken
  }
)

错误

ActionView::Template::Error (undefined method `prev_page_token' for nil:NilClass):
    1: 
    2: <% if !@search_response.prev_page_token.nil? %>

问题是 Search:list 请求的部分参数没有带 contentDetails。 Search:list 请求中 part 参数的文档是这样解释的:

The part parameter specifies a comma-separated list of one or more search resource properties that the API response will include. Set the parameter value to snippet.

注意上面写着:

one or more search resource properties

但搜索资源不包含 contentDetails 属性。所以我认为您可能会收到 badRequest (400) 回复。

但是您确实在视频资源的 contentDetails 属性 中获取了视频的持续时间。


更新

好的,如果你决定使用Videos: list API,这样你就可以通过一个请求获得搜索结果中所有视频的contentDetails,这是一个方法(我假设请求得到成功响应):

# Get the search result like you did.
@search_response = client.execute!(
  :api_method => youtube.search.list,
  :parameters => {
    :part => 'id',
    :q => 'cats',
    :maxResults => 20,
    :order => 'date',
    :pageToken => pageToken
  }
)

# Extract the ids of only the videos in the search result and make
# a comma separated list. Note if there aren't any videos in the search
# result the ids will contain an empty string.
ids = @search_response.items.select do |item|
  # You only want the 'videos'.
  item.id.kind == 'youtube#video'
end.map do |video|
  # Gets the video's id.
  video.id.videoId
end.join(',')

# Now use it to get the list of videos with content details from 
# Videos: list.
@videos = client.execute!(
  :api_method => youtube.video.list,
  :parameters => {
    # Whatever you want from a Video resource.
    :part => 'snippet, contentDetails',
    :id => ids
  }
) 

请注意,这些视频与您在一次搜索中获得的视频相对应(您在上面执行的一次搜索),我不确定结果的顺序是否与搜索结果相同。我认为您现在可以使用 @videos 来获取视频的详细信息,而不是使用 @search_response,但是您将不得不依赖 @search_response 来控制查询和分页等搜索参数。