113

I'm using YouTube API v3 to search YouTube.

https://developers.google.com/youtube/v3/docs/search

As you can see, the response JSON doesn't contains video durations. Is there way to get video durations?

Preferably not calling an API for each element in the result again (unless that's the only way to get durations).

Arad Alvand
  • 8,607
  • 10
  • 51
  • 71
Rukshan
  • 7,902
  • 6
  • 43
  • 61

7 Answers7

158

You will have to make a call to the YouTube data API's video resource after you make the search call. You can put up to 50 video IDs in a search, so you won't have to call it for each element.

https://developers.google.com/youtube/v3/docs/videos/list

You'll want to set part=contentDetails, because the duration is there.

For example, the following call:

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

Gives this result:

{
 "kind": "youtube#videoListResponse",
 "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/ny1S4th-ku477VARrY_U4tIqcTw\"",
 "items": [
  {

   "id": "9bZkp7q19f0",
   "kind": "youtube#video",
   "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/HN8ILnw-DBXyCcTsc7JG0z51BGg\"",
   "contentDetails": {
    "duration": "PT4M13S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "false",
    "licensedContent": true,
    "regionRestriction": {
     "blocked": [
      "DE"
     ]
    }
   }
  }
 ]
}

The time is formatted as an ISO 8601 string. PT stands for Time Duration, 4M is 4 minutes, and 13S is 13 seconds.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt Koskela
  • 5,269
  • 3
  • 26
  • 29
  • 5
    What is this time format ? Is it a standard which Objective C supports? – Rukshan Mar 30 '13 at 17:28
  • 3
    Late comment, but maybe you'd like to star and keep an eye on this ticket requesting durations be included in the search response: https://code.google.com/p/gdata-issues/issues/detail?id=4294 – Andrew Nguyen Mar 06 '14 at 06:54
  • 3
    @Andrew - it is ISO 8601 formatted. I agree that it looks pretty atrocious, but at least it can be easily converted in any language - just look up ISO 8601 converter. – Matt Koskela May 07 '15 at 01:05
  • 3
    For Python, a great library to convert the duration is [aniso8601](https://pypi.python.org/pypi/aniso8601/0.70). It returns a `datetime.timedelta`, which can be formatted to basically anything. – arnaudoff May 30 '15 at 22:28
  • ISO 8601 might sound all nice because it's standard but sorry to break the news, it's not. Apparently Youtube uses a non-standard version of 8601 which includes weeks between days and months which introduces another problematic point into the format. The changing length of months (in both days and weeks) means the actual length of the video can't even be calculated with complete sureness. – sim642 Jun 01 '15 at 12:16
  • 4
    What videos are weeks long on YouTube?!? – Matt Koskela Jun 01 '15 at 15:52
  • Hello, the awnser above is correct and it is able to get the duration for one element by video id. How can i get durations for many videos in single request? – Stavros Koureas May 02 '16 at 16:11
  • 1
    @s19k15: you can pass a comma separated list of id's in the API call I mentioned – Matt Koskela May 06 '16 at 21:01
  • @Matt Koskela Do I need to oAuth this request or can I just use my client_id as the key. SoundCloud APi allows you to do this when reading information about a track. I was hoping that YouTube would do the same. I get an authentication error, when I use my client_id as the value for the key URL variable? – Charles Robertson Aug 09 '16 at 15:27
  • 1
    @Matt Koskela Doh. Sorry Matt. I have just found out that an API key & a client id are two very different things. The API key makes my life a lot easier. I am now going to research all the different queries I can make with this key. Thanks for pointing me in the right direction. This is a real bombshell moment. It looks like I have been trying to oAuth everything unneccessarily... – Charles Robertson Aug 09 '16 at 16:04
  • use iso8601-duration to parse iso8601 if you use node – Feng Liu Jul 24 '18 at 06:39
  • PT = Period Time – ml59 Feb 15 '23 at 22:59
19

I got it!

$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vId&key=dldfsd981asGhkxHxFf6JqyNrTqIeJ9sjMKFcX4");

$duration = json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
    $vTime= $vidTime['contentDetails']['duration'];
}

There it returns the time for YouTube API version 3 (the key is made up by the way ;). I used $vId that I had gotten off of the returned list of the videos from the channel I am showing the videos from...

It works. Google REALLY needs to include the duration in the snippet so you can get it all with one call instead of two... it's on their 'wontfix' list.

Community
  • 1
  • 1
John
  • 195
  • 1
  • 11
6

I wrote the following class to get YouTube video duration using the YouTube API v3 (it returns thumbnails as well):

class Youtube
{
    static $api_key = '<API_KEY>';
    static $api_base = 'https://www.googleapis.com/youtube/v3/videos';
    static $thumbnail_base = 'https://i.ytimg.com/vi/';

    // $vid - video id in youtube
    // returns - video info
    public static function getVideoInfo($vid)
    {
        $params = array(
            'part' => 'contentDetails',
            'id' => $vid,
            'key' => self::$api_key,
        );

        $api_url = Youtube::$api_base . '?' . http_build_query($params);
        $result = json_decode(@file_get_contents($api_url), true);

        if(empty($result['items'][0]['contentDetails']))
            return null;
        $vinfo = $result['items'][0]['contentDetails'];

        $interval = new DateInterval($vinfo['duration']);
        $vinfo['duration_sec'] = $interval->h * 3600 + $interval->i * 60 + $interval->s;

        $vinfo['thumbnail']['default']       = self::$thumbnail_base . $vid . '/default.jpg';
        $vinfo['thumbnail']['mqDefault']     = self::$thumbnail_base . $vid . '/mqdefault.jpg';
        $vinfo['thumbnail']['hqDefault']     = self::$thumbnail_base . $vid . '/hqdefault.jpg';
        $vinfo['thumbnail']['sdDefault']     = self::$thumbnail_base . $vid . '/sddefault.jpg';
        $vinfo['thumbnail']['maxresDefault'] = self::$thumbnail_base . $vid . '/maxresdefault.jpg';

        return $vinfo;
    }
}

Please note that you'll need API_KEY to use the YouTube API:

  1. Create a new project here: https://console.developers.google.com/project
  2. Enable "YouTube Data API" under "APIs & auth" -> APIs
  3. Create a new server key under "APIs & auth" -> Credentials
Dima L.
  • 3,443
  • 33
  • 30
3

This code extracts the YouTube video duration using the YouTube API v3 by passing a video ID. It worked for me.

<?php
    function getDuration($videoID){
       $apikey = "YOUR-Youtube-API-KEY"; // Like this AIcvSyBsLA8znZn-i-aPLWFrsPOlWMkEyVaXAcv
       $dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$videoID&key=$apikey");
       $VidDuration =json_decode($dur, true);
       foreach ($VidDuration['items'] as $vidTime)
       {
           $VidDuration= $vidTime['contentDetails']['duration'];
       }
       preg_match_all('/(\d+)/',$VidDuration,$parts);
       return $parts[0][0] . ":" .
              $parts[0][1] . ":".
              $parts[0][2]; // Return 1:11:46 (i.e.) HH:MM:SS
    }

    echo getDuration("zyeubYQxHyY"); // Video ID
?>

You can get your domain's own YouTube API key on https://console.developers.google.com and generate credentials for your own requirement.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

You can get the duration from the 'contentDetails' field in the json response.

enter image description here

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
1

Duration in seconds using Python 2.7 and the YouTube API v3:

    try:        
        dur = entry['contentDetails']['duration']
        try:
            minutes = int(dur[2:4]) * 60
        except:
            minutes = 0
        try:
            hours = int(dur[:2]) * 60 * 60
        except:
            hours = 0

        secs = int(dur[5:7])
        print hours, minutes, secs
        video.duration = hours + minutes + secs
        print video.duration
    except Exception as e:
        print "Couldnt extract time: %s" % e
        pass
andrea-f
  • 1,045
  • 9
  • 23
1

Youtube data 3 API , duration string to seconds conversion in Python

Example:

convert_YouTube_duration_to_seconds('P2DT1S')
172801

convert_YouTube_duration_to_seconds('PT2H12M51S')
7971

def convert_YouTube_duration_to_seconds(duration):
   day_time = duration.split('T')
   day_duration = day_time[0].replace('P', '')
   day_list = day_duration.split('D')
   if len(day_list) == 2:
      day = int(day_list[0]) * 60 * 60 * 24
      day_list = day_list[1]
   else:
      day = 0
      day_list = day_list[0]
   hour_list = day_time[1].split('H')
   if len(hour_list) == 2:
      hour = int(hour_list[0]) * 60 * 60
      hour_list = hour_list[1]
   else:
      hour = 0
      hour_list = hour_list[0]
   minute_list = hour_list.split('M')
   if len(minute_list) == 2:
      minute = int(minute_list[0]) * 60
      minute_list = minute_list[1]
   else:
      minute = 0
      minute_list = minute_list[0]
   second_list = minute_list.split('S')
   if len(second_list) == 2:
      second = int(second_list[0])
   else:
      second = 0
   return day + hour + minute + second
Community
  • 1
  • 1