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).
This question is related to
php
objective-c
rest
youtube-api
youtube-data-api
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:
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.
Youtube data 3 API , duration string to seconds conversion in Python
convert_YouTube_duration_to_seconds('P2DT1S')
172801convert_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
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.
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
Source: Stackoverflow.com