Jak uzyskać czas trwania wideo z YouTube API w wersji 3?

Używam YouTube API v3 do wyszukiwania YouTube.

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

Jak widać, odpowiedź JSON nie zawiera czas trwania wideo. Czy jest sposób, aby uzyskać czas trwania wideo?

Najlepiej nie wywoływać API dla każdego elementu w wyniku ponownie(chyba, że jest to jedyny sposób, aby uzyskać czas trwania).

Author: Peter Mortensen, 2013-03-24

6 answers

Będziesz musiał wykonać połączenie do zasobów wideo YouTube data API po dokonaniu połączenia wyszukiwania. Możesz umieścić do 50 identyfikatorów wideo w wyszukiwarce, więc nie będziesz musiał go wywoływać dla każdego elementu.

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

Będziesz chciał ustawić part=contentDetails, ponieważ czas trwania jest tam.

Na przykład, następujące wywołanie:

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

Daje wynik:

{
 "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"
     ]
    }
   }
  }
 ]
}

Czas jest sformatowany jako ciąg ISO 8601. PT oznacza czas trwania, 4M to 4 minuty, a 13S to 13 sekund.

 82
Author: Matt Koskela,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-19 18:22:57

Mam!

$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'];

Tam zwraca czas dla YouTube API w wersji 3 (klucz jest wymyślony przy okazji ;). Użyłem $vId, że usunąłem listę zwróconych filmów z kanału, z którego wyświetlam filmy...

To działa... :) Google naprawdę musi uwzględnić czas trwania w fragmencie, aby można było uzyskać to wszystko za pomocą jednego połączenia zamiast dwóch... westchnienie....... jest na ich liście "wontfix".
 12
Author: John,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-19 18:37:56

Napisałem następującą klasę, aby uzyskać czas trwania wideo YouTube za pomocą YouTube API v3 (zwraca również miniatury):

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;
    }
}

Pamiętaj, że aby korzystać z API YouTube, musisz użyć API_KEY:

  1. Utwórz nowy projekt tutaj: https://console.developers.google.com/project
  2. włącz "YouTube Data API" w "API & auth" - > API
  3. Utwórz nowy klucz serwera pod "API & auth" - > poświadczenia
 6
Author: Dima L.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-21 05:05:30

Uzyskiwanie czasu trwania w godzinach, minutach i sekundach przy użyciu regex (testowane w Pythonie 3)

import re
def parse_ISO8601(dur):
    test1 = rex("PT(.+?)H", dur)
    if test1:
        return int(test1.group(1))*3600
    test2 = rex("PT(.+?)H(.+?)M",dur)
    if test2:
        h,m = [int(x) for x in test2.groups()]
        return 3600*h+60*m
    test3 = rex("PT(.+?)H(.+?)S",dur)
    if test3:
        h,s = [int(x) for x in test3.groups()]
        return 3600*h+s
    test4 = rex("PT(.+?)H(.+?)M(.+?)S",dur)
    if test4:
        h,m,s = [int(x) for x in test4.groups()]
        return 3600*h+60*h+s
    test5 = rex("PT(.+?)M", dur)
    if test5:
        return int(test5.group(1))*60
    test6 = rex("PT(.+?)M(.+?)S",dur)
    if test6:
        m,s = [int(x) for x in test6.groups()]
        return 60*m+s
    test7 = rex("PT(.+?)S",dur)
    if test7:
        return int(test7.group(1))
    print("CAN'T PARSE FUCKING GOOGLE FORMATTING:",dur)
    return False #I'm out ...
 2
Author: mikroskeem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-19 11:52:15

Ten kod wyodrębnia czas trwania wideo YouTube za pomocą interfejsu API YouTube v3, przekazując identyfikator wideo. U mnie zadziałało.

<?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
?>

Możesz uzyskać własny klucz API YouTube swojej domeny na https://console.developers.google.com i wygenerować poświadczenia dla własnych wymagań.

 2
Author: Vignesh Waran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-19 18:34:07

Czas trwania w sekundach przy użyciu Pythona 2.7 i 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
 0
Author: andrea-f,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-11 23:27:10