Search code examples
javayoutube-data-api

How do I retrieve durations of videos through Youtube API v3 YouTube.PlaylistItems.List request?


I'm using Youtube API v3 (Java) to access Youtube videos, playlists. Below is a sample code:

YouTube.PlaylistItems.List request = 
youtube.playlistItems().list("id,contentDetails,snippet");
request.setPlaylistId(/*playlist id*/);                
request.setFields("items(contentDetails/videoId,snippet/title,snippet/publishedAt, 
snippet/description),nextPageToken,pageInfo");

PlaylistItemListResponse result = request.execute();

Now I can get a title of each video from a playlist like this:

for (PlaylistItem item : result.getItems()) {
    item.getSnippet().getTitle();
    // But how can I retrieve a duration now?
}

I have tried different methods to retrieve duration of the videos, but they all returned null. How do I get a duration?


Solution

  • Video duration can be found inside contentDetails part of .videos().list(). Unfortunatelly, you cann't get video duration through PlayListItem as in your example, you can get only video_id.

    So, you can extract all video_id that playlist has and make an additional call to receive video data, like:

    https://www.googleapis.com/youtube/v3/videos?id=9bZkp7q19f0&part=contentDetails&key={YOUR_API_KEY}
    

    as a result, you will get something like:

    "contentDetails": {
        "duration": "PT4M13S",
        "dimension": "2d",
        "definition": "hd",
        "caption": "false",
        "licensedContent": true,
        "regionRestriction": {
         "blocked": [
          "DE"
         ]
     }
    

    There is a field duration inside.

    You can play with all YouTube API here