ruby-on-rails - 即使是搜索结果,我也可以从YouTube API3.0获取视频的时长吗?

标签 ruby-on-rails ruby ruby-on-rails-3 youtube youtube-api

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

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

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

零件部分中有两个以上时,似乎会发生错误。
如果我将其保留为: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请求的part参数没有采用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来控制搜索参数,例如查询和分页。

关于ruby-on-rails - 即使是搜索结果,我也可以从YouTube API3.0获取视频的时长吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31508034/

相关文章:

ruby-on-rails - 访问授权和访问 token 之间的区别

javascript - application.js 找不到 jquery.ui.effect-blind

ruby-on-rails - rails : What's a good way to validate links (URLs)?

mysql - 从 rails 中的 mysql 存储过程中获取多个结果集

完全重新安装后,Mysql 错误 ERROR 2002 (HY000) 仍然存在

ruby-on-rails - 使用 pg_restore 数据转储创建新的 Rails 应用程序

ruby-on-rails - Rails 更新操作的路由助手是什么?

ruby-on-rails - Ruby 中的方法定义和命名约定

ruby-on-rails - Rails 3.1 和 sprockets 使使用 firebug 进行调试变得更加困难?

java - 分段上传不适用于 android + rails