php 如何使用 YouTube API 版本 3 获取视频时长?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15596753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get video durations with YouTube API version 3?
提问by sleepwalkerfx
I'm using YouTube API v3 to search YouTube.
我正在使用 YouTube API v3 来搜索 YouTube。
https://developers.google.com/youtube/v3/docs/search
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?
如您所见,响应 JSON 不包含视频时长。有没有办法获得视频时长?
Preferably not calling an API for each element in the result again (unless that's the only way to get durations).
最好不要再次为结果中的每个元素调用 API(除非这是获取持续时间的唯一方法)。
回答by Matt Koskela
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.
在进行搜索调用后,您必须调用 YouTube 数据 API 的视频资源。您最多可以在搜索中放置 50 个视频 ID,因此您不必为每个元素调用它。
https://developers.google.com/youtube/v3/docs/videos/list
https://developers.google.com/youtube/v3/docs/videos/list
You'll want to set part=contentDetails, because the duration is there.
你会想要设置part=contentDetails,因为持续时间在那里。
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.
时间格式为 ISO 8601 字符串。PT代表Time Duration,4M是4分钟,13S是13秒。
回答by John
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 $vIdthat I had gotten off of the returned list of the videos from the channel I am showing the videos from...
在那里它返回 YouTube API 版本 3 的时间(顺便说一下,密钥是由;)。我曾经使用过$vId,我已经从我正在播放的频道中返回的视频列表中删除了...
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.
有用。谷歌真的需要在代码片段中包含持续时间,这样你就可以通过一次调用而不是两次调用来获得所有内容......它在他们的“wontfix”列表中。
回答by Dima L.
I wrote the following class to get YouTube video duration using the YouTube API v3 (it returns thumbnails as well):
我编写了以下类来使用 YouTube API v3 获取 YouTube 视频时长(它也返回缩略图):
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:
请注意,您需要 API_KEY 才能使用 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
- 在此处创建一个新项目:https: //console.developers.google.com/project
- 在“APIs & auth”-> APIs 下启用“YouTube Data API”
- 在“APIs & auth”-> Credentials 下创建一个新的服务器密钥
回答by Vignesh Chinnaiyan
This code extracts the YouTube video duration using the YouTube API v3 by passing a video ID. It worked for me.
此代码通过传递视频 ID 使用 YouTube API v3 提取 YouTube 视频时长。它对我有用。
<?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.comand generate credentials for your own requirement.
您可以在https://console.developers.google.com上获取您的域自己的 YouTube API 密钥,并根据您自己的要求生成凭据。
回答by Maurya Allimuthu
回答by andrea-f
Duration in seconds using Python 2.7 and the YouTube API v3:
使用 Python 2.7 和 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
回答by Maurya Allimuthu
Youtube data 3 API , duration string to seconds conversion in Python
Youtube 数据 3 API,持续时间字符串到 Python 中的秒数转换
Example:
例子:
convert_YouTube_duration_to_seconds('P2DT1S')
172801convert_YouTube_duration_to_seconds('PT2H12M51S')
7971
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


