1

Problem Statement

1)I am a beginner at implementing youtube api and I want to retrieve VideoMetaData such as duration of video and stream url.

MyAnalysis :

1)I have used the youtube api to retrieve this metaData such as Video Tilte,VideoID and creation Date.

2)The problem is I am not able to see other data such as Video duration and stream url in the Response.

//Also,StartTime and EndTime has been depreciated.So I cannot find duration

Then,how can I fetch these details related to video.

Below is the response I am getting.

https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlistItems.list?part=snippet%252CcontentDetails&maxResults=25&playlistId=PL8WtjSOdakGuBu0q9EKLXndc4jcAQxs2Y&_h=1&

Code for the Same :

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

}      
}
}
Jalaj Chawla
  • 189
  • 1
  • 3
  • 18

3 Answers3

2

I had the same issue and proceeded as bellow to retrieve the duration. Note that i had to make a separate request just for video duration. First i had to read the json response using the video ID and of course the "part" and my APIkey. the part here is "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;

}

Then i used JSONObject Class from org.json api to parse the json and get the duration

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

You can notice that i used java.time.Duration object to parse the duration format to seconds. it's available id JDK 1.8 I hope it helps someone

daniel rubambura
  • 545
  • 6
  • 12
1

As stated in this thread, you may get the duration using the part=contentDetails. Sample response:

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

Regarding stream URL, check this cdn.ingestionInfo.ingestionAddress.

The primary ingestion URL that you should use to stream video to YouTube. You must stream video to this URL.

Depending on which application or tool you use to encode your video stream, you may need to enter the stream URL and stream name separately or you may need to concatenate them in the following format:

STREAM_URL/STREAM_NAME

Check these Java Code Samples.

Community
  • 1
  • 1
abielita
  • 13,147
  • 2
  • 17
  • 59
0

I used th following changes in the Code to access Video MetaData

1)Change was done to retrieve url where I concatinated the url along with videoId

2)Made a Connection with youtube api again to retrieve video metadata

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);
Jalaj Chawla
  • 189
  • 1
  • 3
  • 18