【发布时间】:2020-11-21 11:15:42
【问题描述】:
我正在使用 YouTubeData Api v3 从搜索结果中获取视频的 ID、标题、描述和缩略图。现在我还想获取视频的持续时间,这是我无法使用以下代码实现的。
如何获取视频的时长?我也设置了部分和字段,如代码所示以接收属性。
private int youTubeConnector() {
try {
youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) {
}
}).setApplicationName(getResources().getString(R.string.app_name)).build();
} catch(ExceptionInInitializerError e){
e.printStackTrace();
return -1;
} catch(RuntimeException e){
e.printStackTrace();
return -1;
} catch(Exception e){
e.printStackTrace();
return -1;
}
try {
query = youtube.search().list("id,snippet,contentDetails");
query.setKey(Constants.YOUTUBE);
query.setType("video");
query.setFields("items(id/kind,id/videoId,snippet/title,snippet/description,snippet/thumbnails/high/url,contentDetails/duration),nextPageToken,prevPageToken,pageInfo");
return 1;
} catch (IOException e) {
e.printStackTrace();
return -1;
} catch (Exception e){
e.printStackTrace();
return -1;
}
}
public List<YouTubeVideoItem> search(String keywords) {
query.setQ(keywords);
query.setMaxResults(YOUTUBE_MAXRESULTS);
if(nextPage == true) {
query.setPageToken(nextPageToken);
nextPage = false;
}
else if(previousPage == true) {
query.setPageToken(previousPageToken);
previousPage = false;
}
try {
SearchListResponse response = query.execute();
nextPageToken = response.getNextPageToken();
previousPageToken = response.getPrevPageToken();
List<SearchResult> results = response.getItems();
List<YouTubeVideoItem> items = new ArrayList<YouTubeVideoItem>();
if(results != null) {
items = setItemsList(results.iterator());
}
return items;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e){
e.printStackTrace();
return null;
}
}
private List<YouTubeVideoItem> setItemsList(Iterator<SearchResult> iteratorSearchResults) {
List<YouTubeVideoItem> tempSetItems = new ArrayList<>();
while(iteratorSearchResults.hasNext()) {
SearchResult singleVideo = iteratorSearchResults.next();
ResourceId rId = singleVideo.getId();
try{
if (rId.getKind().equals("youtube#video")) {
YouTubeVideoItem item = new YouTubeVideoItem();
Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getHigh();
item.setId(singleVideo.getId().getVideoId());
item.setTitle(singleVideo.getSnippet().getTitle());
item.setDescription(singleVideo.getSnippet().getDescription());
item.setThumbnailURL(thumbnail.getUrl());
tempSetItems.add(item);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return tempSetItems;
}
【问题讨论】:
标签: android json youtube youtube-data-api google-apis-explorer