我知道,如果直接获取特定视频,它可以获得持续时间。
如果是搜索结果怎么办?
我很确定它可以为我们提供视频的标题,唯一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/