¿Cómo puedo obtener duraciones de vídeo con YouTube API versión 3?


Estoy usando YouTube API v3 para buscar en YouTube.

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

Como puede ver, el JSON de respuesta no contiene duraciones de video. ¿Hay forma de obtener duraciones de video?

Preferiblemente no llamar a una API para cada elemento en el resultado de nuevo (a menos que esa sea la única manera de obtener duraciones).

Author: Peter Mortensen, 2013-03-24

6 answers

Tendrá que realizar una llamada al recurso de vídeo de la API de datos de YouTube después de realizar la llamada de búsqueda. Puede poner hasta 50 ID de vídeo en una búsqueda, por lo que no tendrá que llamarlo para cada elemento.

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

Querrás establecer part=contentDetails, porque la duración está ahí.

Por ejemplo, la siguiente llamada:

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

Da este resultado:

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

La hora se formatea como una cadena ISO 8601. PT significa Duración de tiempo, 4M es 4 minutos, y 13S es 13 segundos.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-19 18:22:57

¡Lo tengo!

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

Allí devuelve el tiempo para la versión 3 de la API de YouTube (la clave está hecha por cierto;). Usé $vId que había salido de la lista devuelta de los videos del canal desde el que estoy mostrando los videos...

Funciona... :) Google REALMENTE necesita incluir la duración en el fragmento para que pueda obtener todo con una llamada en lugar de dos... suspiro....... está en su lista de '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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-19 18:37:56

Escribí la siguiente clase para obtener la duración del video de YouTube usando la API de YouTube v3 (también devuelve miniaturas):

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

Tenga en cuenta que necesitará API_KEY para usar la API de YouTube:

  1. Crea un nuevo proyecto aquí: https://console.developers.google.com/project
  2. Habilite "YouTube Data API" en "APIs & auth" - > APIs
  3. Crear una nueva clave de servidor en "APIs & auth" - > Credenciales
 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-21 05:05:30

Obtener la duración en horas, minutos y segundos usando expresiones regulares (probado en Python 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-19 11:52:15

Este código extrae la duración del vídeo de YouTube usando la API de YouTube v3 pasando un ID de vídeo. Funcionó para mí.

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

Puede obtener la clave API de YouTube de su dominio en https://console.developers.google.com y generar credenciales para su propio requerimiento.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-19 18:34:07

Duración en segundos usando Python 2.7 y la API de YouTube 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-11 23:27:10