无法使用播放列表项 API 检索 VideoMetaData,例如视频持续时间和流 url?
Posted
技术标签:
【中文标题】无法使用播放列表项 API 检索 VideoMetaData,例如视频持续时间和流 url?【英文标题】:Unable to retrieve VideoMetaData such as duration of video and stream url using playlist Items API? 【发布时间】:2018-03-09 06:31:30 【问题描述】:问题陈述
1)我是实现 youtube api 的初学者,我想检索 VideoMetaData,例如视频时长和流 url。
我的分析:
1)我已使用 youtube api 检索此元数据,例如 Video Tilte、VideoID 和创建日期。
2)问题是我无法在响应中看到其他数据,例如视频时长和流 url。
//另外,StartTime和EndTime已经被贬值了,所以我找不到持续时间
那么,如何获取这些与视频相关的详细信息。
以下是我收到的回复。
https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlistItems.list?part=snippet%252CcontentDetails&maxResults=25&playlistId=PL8WtjSOdakGuBu0q9EKLXndc4jcAQxs2Y&_h=1&
相同的代码:
public class Search1
private static YouTube.PlaylistItems.List playlistItemRequest;
private static String PLAYLIST_ID = "PL8WtjSOdakGuBu0q9EKLXndc4jcAQxs2Y";
private static final Long NUMBER_OF_VIDEOS_RETURNED = (long) 10;
private static String apiKey="AIzaSyDJAaPLW5wbWdfKX6CjfvSo5yrF3K3rlwc";
private static YouTube youtube;
public static void main(String s[])
youtube = new YouTube.Builder(new NetHttpTransport(),
new JacksonFactory(), new HttpRequestInitializer()
@Override
public void initialize(HttpRequest hr) throws IOException
).setApplicationName("youtube-cmdline-search-sample").build();
List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
try
playlistItemRequest = youtube.playlistItems().list("snippet,contentDetails");
playlistItemRequest.setPlaylistId(PLAYLIST_ID);
playlistItemRequest.setFields("items(snippet/title,snippet/playlistId,snippet/publishedAt,snippet/description,snippet/thumbnails/default/url,contentDetails/videoId,contentDetails/startAt,contentDetails/endAt,contentDetails/videoPublishedAt),nextPageToken,pageInfo");
playlistItemRequest.setKey(apiKey);
// videoItem.setId(item.getContentDetails().getVideoId());
String nextToken = "";
do
playlistItemRequest.setPageToken(nextToken);
PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();
playlistItemList.addAll(playlistItemResult.getItems());
nextToken = playlistItemResult.getNextPageToken();
while (nextToken != null);
catch(IOException e)
System.out.println("Exception"+e);
Iterator iteratorSearchResults=playlistItemList.iterator();
while (iteratorSearchResults.hasNext())
PlaylistItem playlist = (PlaylistItem) iteratorSearchResults.next();
// String duration=(playlist.getContentDetails().getStartAt()-playlist.getContentDetails().getEndAt());
System.out.println(" Title: " + playlist.getSnippet().getTitle());
System.out.println(" Video Created Date" + playlist.getContentDetails().getVideoPublishedAt());
System.out.println(" PlayList ID: " + playlist.getSnippet().getPlaylistId());
System.out.println(" Video ID: " + playlist.getContentDetails().getVideoId());
System.out.println(" Stream url of PlayList: ");
System.out.println(" Start Time: " + playlist.getContentDetails().getStartAt());
System.out.println(" End Time: " + playlist.getContentDetails().getEndAt());
System.out.println(" Duration " );
【问题讨论】:
【参考方案1】:我遇到了同样的问题,并按如下方式检索持续时间。请注意,我必须为视频持续时间单独提出请求。 首先我必须使用视频 ID 读取 json 响应,当然还有“部分”和我的 APIkey。 这里的部分是“contentDetails”
String retrieveVideoJSON(String videoID, String part, String APIkey)
String postURL = "https://www.googleapis.com/youtube/v3/videos?id=" + videoID + "&part=" + part + "&key=" + APIkey;
String output = "";
try
URL url = new URL(postURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader br1 = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String line1;
while ((line1 = br1.readLine()) != null)
output = output + line1;
conn.disconnect();
br1.close();
catch (IOException e)
System.out.println("\ne = " + e.getMessage() + "\n");
return output;
然后我使用 org.json api 中的 JSONObject 类来解析 json 并获取持续时间
String videoJSON = retrieveVideoJSON(videoID, "contentDetails", myAPIkey);
JSONObject jsonObj = new JSONObject(videoJSON).getJSONArray("items").getJSONObject(0).getJSONObject("contentDetails");
long seconds = Duration.parse(jsonObj.getString("duration")).getSeconds();
您可以注意到我使用 java.time.Duration 对象将持续时间格式解析为秒。 它可用 id JDK 1.8 我希望它可以帮助某人
【讨论】:
【参考方案2】:我在代码中使用了以下更改来访问视频元数据
1) 已完成更改以检索我将 url 与 videoId 连接在一起的 url
2)再次与youtube api建立连接以检索视频元数据
public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");
static String url="http://eventapi-dev.wynk.in/tv/events/v1/event";
static OkHttpClient client = new OkHttpClient();
private static YouTube.PlaylistItems.List playlistItemRequest;
private static String PLAYLIST_ID = "PL8WtjSOdakGuBu0q9EKLXndc4jcAQxs2Y";
private static String apiKey="AIzaSyDJAaPLW5wbWdfKX6CjfvSo5yrF3K3rlwc";
private static YouTube youtube;
public static void main(String s[]) throws IOException
//Create a Bean
WynkData wd=new WynkData();
String videoID=null;
//Make a Connection with YouTubeApi
youtube = new YouTube.Builder(new NetHttpTransport(),
new JacksonFactory(), new HttpRequestInitializer()
@Override
public void initialize(HttpRequest hr) throws IOException
).setApplicationName("youtube-cmdline-search-sample").build();
List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
try
//Specify the search Params
playlistItemRequest = youtube.playlistItems().list("snippet,contentDetails");
playlistItemRequest.setPlaylistId(PLAYLIST_ID);
playlistItemRequest.setFields("items(snippet/title,snippet/playlistId,snippet/publishedAt,contentDetails/videoId,contentDetails/videoPublishedAt),nextPageToken,pageInfo");
playlistItemRequest.setKey(apiKey);
String nextToken = "";
do
// Execute and add in a list
playlistItemRequest.setPageToken(nextToken);
PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();
playlistItemList.addAll(playlistItemResult.getItems());
nextToken = playlistItemResult.getNextPageToken();
while (nextToken != null);
catch(IOException e)
System.out.println("Exception"+e);
// Retrieve the Recods
Iterator<PlaylistItem> iteratorSearchResults=playlistItemList.iterator();
while (iteratorSearchResults.hasNext())
PlaylistItem playlist = (PlaylistItem) iteratorSearchResults.next();
wd.setTitle(playlist.getSnippet().getTitle());
System.out.println(" Title: " + playlist.getSnippet().getTitle());
System.out.println(" Video Created Date" + playlist.getContentDetails().getVideoPublishedAt());
wd.setCreatedDate(playlist.getContentDetails().getVideoPublishedAt());
//更改1
System.out.println("Video Url https://www.youtube.com/watch?v="+playlist.getContentDetails().getVideoId());
videoID=playlist.getContentDetails().getVideoId();
System.out.println(" Stream url of PlayList: ");
String streamurl="https://www.youtube.com/watch?v="+videoID;
wd.setStreamurl(streamurl);
System.out.println(" PlayList ID: " + playlist.getSnippet().getPlaylistId());
System.out.println(" Video ID: " + playlist.getContentDetails().getVideoId());
变化2
// Make a Connection with YouTube Api again to retrieve Video Duration
System.out.println(videoID);
final String videoId = videoID;
YouTube.Videos.List videoRequest = youtube.videos().list("snippet,statistics,contentDetails");
videoRequest.setId(videoId);
videoRequest.setKey(apiKey);
VideoListResponse listResponse = videoRequest.execute();
List<Video> videoList = listResponse.getItems();
Video targetVideo = videoList.iterator().next();
System.out.println(targetVideo.getSnippet().getTitle());
System.out.println(targetVideo.getStatistics().getViewCount());
String duration=targetVideo.getContentDetails().getDuration();
StringBuilder sb=new StringBuilder(duration);
duration=sb.substring(2).replaceAll("[A-Z]",":").toString();
wd.setDuration(duration);
System.out.println(wd);
【讨论】:
【参考方案3】:正如thread 中所述,您可以使用part=contentDetails
获得duration
。样品response:
"contentDetails":
"duration": string,
"dimension": string,
"definition": string,
...
,
关于stream URL
,请查看cdn.ingestionInfo.ingestionAddress
。
用于将视频流式传输到 YouTube 的主要提取 URL。您必须将视频流式传输到此 URL。
根据您用于对视频流进行编码的应用程序或工具,您可能需要分别输入流 URL 和流名称,或者您可能需要将它们以以下格式连接:
STREAM_URL/STREAM_NAME
检查这些Java Code Samples。
【讨论】:
以上是关于无法使用播放列表项 API 检索 VideoMetaData,例如视频持续时间和流 url?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 youtube api 一次更新多个播放列表项的位置?