无法使用播放列表Items API检索VideoMetaData,例如视频和流网址的持续时间?

时间:2017-09-27 17:02:17

标签: java json youtube-api

问题陈述

1)我是实施youtube api的初学者,我想检索VideoMetaData,例如视频和流网址的持续时间。

MyAnalysis:

1)我使用了youtube api来检索这个元数据,例如Video Tilte,VideoID和创建日期。

2)问题是我无法在响应中看到其他数据,如视频时长和流网址。

//此外,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 " );

}      
}
}

3 个答案:

答案 0 :(得分:1)

thread所述,您可以使用part=contentDetails获取duration。示例response

"contentDetails": {
    "duration": string,
    "dimension": string,
    "definition": string,
    ...
    },

关于stream URL,请检查此cdn.ingestionInfo.ingestionAddress

  

您应该用于将视频流式传输到YouTube的主要提取网址。您必须将视频流式传输到此网址。

     

根据您用于对视频流进行编码的应用程序或工具,您可能需要单独输入流URL和流名称,或者您可能需要按以下格式连接它们:

     

STREAM_URL/STREAM_NAME

检查这些Java Code Samples

答案 1 :(得分:1)

我遇到了同样的问题,然后像下面这样继续检索持续时间。请注意,我只针对视频时长提出了单独的要求。 首先,我必须使用视频ID阅读json响应,当然还要阅读“ part”和我的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 Class解析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 :(得分:0)

我在代码中使用了以下更改来访问视频元数据

1)进行了更改以检索url,其中我将url与videoId连接在一起

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());

// Change1

 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());
        }

<强> Change2

//          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);
相关问题