2012-02-06 20 views
5

Poszukuję funkcji, która pobierze czas trwania filmu z adresu URL. Czytałem kilka tutoriali, ale nie rozumiem. Umieszczam filmy w mojej witrynie za pomocą adresu URL i mam funkcję, która ściąga miniaturkę i chcę po prostu czegoś podobnego, co daje czas trwania. Oto jak uzyskać kciuka ...Uzyskaj czas trwania z adresu URL na youtube

function get_youtube_screen_link($url = '', $type = 'default', $echo = true) { 
if(empty($url)) 
    return false; 

if(!isset($type)) 
    $type = ''; 

$url = esc_url($url); 

preg_match("|[\\?&]v=([^&#]*)|",$url,$vid_id); 

if(!isset($vid_id[1])) 
    return false; 

$img_server_num = 'i'. rand(1,4); 

switch($type) { 
    case 'large': 
     $img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/0.jpg"; 
     break; 
    case 'first': 
     // Thumbnail of the first frame 
     $img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/1.jpg"; 
     break; 
    case 'small': 
     // Thumbnail of a later frame(i'm not sure how they determine this) 
     $img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/2.jpg"; 
     break; 
    case 'default': 
    case '': 
    default: 
     $img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/default.jpg"; 
     break; 
} 
if($echo) 
    echo $img_link; 
else 
    return $img_link; 

}

Odpowiedz

11

Można użyć coś takiego:

<?php 

    function getDuration($url){ 

     parse_str(parse_url($url,PHP_URL_QUERY),$arr); 
     $video_id=$arr['v']; 


     [email protected]_get_contents('http://gdata.youtube.com/feeds/api/videos/'.$video_id.'?v=2&alt=jsonc'); 
     if (false===$data) return false; 

     $obj=json_decode($data); 

     return $obj->data->duration; 
    } 

    echo getDuration('http://www.youtube.com/watch?v=rFQc7VRJowk'); 

?> 

która zwraca czas w sekundach filmu.

referencyjny: http://code.google.com/apis/youtube/2.0/developers_guide_protocol.html

Można użyć funkcji takich jak this one zmienić sekund do godzin, minut i sekund.

+0

Potrzebuję $ video_id, aby pobrać go z adresu URL wprowadzonego w niestandardowym polu dla każdego wpisu. –

+0

Zaktualizowałem przykład, aby uzyskać identyfikator video_id z adresu URL – stewe

+0

Użyłem tego jako funkcji i działa, ale jeśli wideo zostało usunięte z youtube, to dostaję błędy tam, gdzie próbuje się wydrukować. W jaki sposób mogę wydać instrukcję if, aby się przed tym zabezpieczyć? –

0

Możesz po prostu użyć formatera czasu, aby zmienić sekundy na dowolny format. tj. Powrót gmdate ("H: i: s", $ obj-> data-> duration);

0
function getYoutubeDuration($videoid) { 
     $xml = simplexml_load_file('https://gdata.youtube.com/feeds/api/videos/' . $videoid . '?v=2'); 
     $result = $xml->xpath('//yt:duration[@seconds]'); 
     $total_seconds = (int) $result[0]->attributes()->seconds; 

     return $total_seconds; 
} 

//now call this pretty function. 
//As parameter I gave a video id to my function and bam! 
echo getYoutubeDuration("y5nKxHn4yVA"); 
+1

Ten punkt końcowy (v2) już nie działa. –

3

youtube API V3


wykorzystanie

echo youtubeVideoDuration('video_url', 'your_api_key'); 
// output: 63 (seconds) 

funkcja

/** 
* Return video duration in seconds. 
* 
* @param $video_url 
* @param $api_key 
* @return integer|null 
*/ 
function youtubeVideoDuration($video_url, $api_key) { 

    // video id from url 
    parse_str(parse_url($video_url, PHP_URL_QUERY), $get_parameters); 
    $video_id = $get_parameters['v']; 

    // video json data 
    $json_result = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$video_id&key=$api_key"); 
    $result = json_decode($json_result, true); 

    // video duration data 
    if (!count($result['items'])) { 
     return null; 
    } 
    $duration_encoded = $result['items'][0]['contentDetails']['duration']; 

    // duration 
    $interval = new DateInterval($duration_encoded); 
    $seconds = $interval->days * 86400 + $interval->h * 3600 + $interval->i * 60 + $interval->s; 

    return $seconds; 
} 
+0

nie działa dla mnie, mówi file_get_content jest zablokowany ze względów bezpieczeństwa –

1

To jest moja funkcja, aby uzyskać czas youtube na sekundę. on jest w 100% pełny pracy. potrzebujesz tylko wideo z YouTube i kluczem API YouTube.

jak dodać youtube klucz API pokaz ten film https://www.youtube.com/watch?v=4AQ9UamPN6E

public static function getYoutubeDuration($id) 
    { 



     $Youtube_KEY=''; 

     $dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id={$id}&key={$Youtube_KEY}"); 

     $vTime=''; 
     $H=0; 
     $M=0; 
     $S=0; 

     $duration = json_decode($dur, true); 
     foreach ($duration['items'] as $vidTime) { 
     $vTime = $vidTime['contentDetails']['duration']; 
     } 

     $vTime = substr($vTime, 2); 
     $exp = explode("H",$vTime); 

     //if explode executed 
     if($exp[0] != $vTime) 
     { 
      $H = $exp[0]; 
      $vTime = $exp[1]; 
     } 

     $exp = explode("M",$vTime); 

     if($exp[0] != $vTime) 
     { 
      $M = $exp[0]; 
      $vTime = $exp[1]; 
     } 

     $exp = explode("S",$vTime); 
     $S = $exp[0]; 


     $H = ($H*3600); 
     $M = ($M*60); 
     $S = ($H+$M+$S); 


     return $S; 

    } 

To jest mój czas, aby funkcja youtube w sekundę. on jest w 100% pełny pracy. potrzebujesz tylko wideo z YouTube i kluczem API YouTube.

jak dodać youtube klucz API pokaz ten film https://www.youtube.com/watch?v=4AQ9UamPN6E

0

1) Trzeba będzie klucz API. Przejdź na numer https://developers.google.com/ i zaloguj się lub utwórz konto, jeśli to konieczne. Po zalogowaniu przejdź do tego linku https://console.developers.google.com/project i kliknij niebieski przycisk UTWÓRZ PROJEKT. Zaczekaj chwilę, gdy Google przygotuje Twój projekt.

2) Będziesz potrzebował hosta z uruchomionym PHP z obsługą file_get_content. Możesz sprawdzić, tworząc nowy skrypt za pomocą "echo php_info();" i sprawdzanie, czy parametr allow_url_fopen ma wartość On. Jeśli tak nie jest, zmień konfigurację lub porozmawiaj ze swoim usługodawcą hostingowym.

<?php 

    $sYouTubeApiKey = "<enter the key you get>"; 
    //Replace This With The Video ID. You can get it from the URL. 
    //ie https://www.youtube.com/XWuUdJo9ubM would be 
    $sVideoId = "XWuUdJo9ubM"; 

    //Get The Video Details From The API. 
    function getVideoDetails ($sVideoId) { 
    global $sYouTubeApiKey; 
    //Generate The API URL 
    $sUrl = "https://www.googleapis.com/youtube/v3/videos?id=".$sVideoId."&key=".$sYouTubeApiKey."&part=contentDetails"; 
    //Perform The Request 
    $sData = file_get_contents($sUrl); 
    //Decode The JSON Response 
    return json_decode($sData); 
    } 

    //Get The Video Duration In Seconds. 
    function getVideoDuration ($sVideoId) { 
    $oData = getVideoDetails($sVideoId); 
    //Deal With No Videos In List 
    if (count($oData->items) < 1) return false; 
    //Get The First Video 
    $oVideo = array_shift($oData->items); 
    //Extract The Duration 
    $sDuration = $oVideo->contentDetails->duration; 
    //Use Regular Expression To Parse The Length 
    $pFields = "'PT(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?'si"; 
    if (preg_match($pFields, $sDuration, $aMatch)) { 
     //Add Up Hours, Minutes, and Seconds 
     return $aMatch[1]*3600 + $aMatch[2]*60 + $aMatch[3]; 
    } 
    } 

    header("Content-Type: text/plain"); 
    $oData = getVideoDetails($sVideoId); 
    print_r($oData); 
    echo "Length: ".getVideoDuration($sVideoId); 
?> 

Mam nadzieję, że to pomoże!

Powiązane problemy