How do I get video durations with YouTube API version 3?
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).
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.
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.
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:
- Create a new project here: https://console.developers.google.com/project
- Enable "YouTube Data API" under "APIs & auth" -> APIs
- Create a new server key under "APIs & auth" -> Credentials
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.
You can get the duration from the 'contentDetails' field in the json response.