2012-02-06 95 views
5

我正在尋找一種可以從網址中提取視頻的YouTube時長的功能。我讀了一些教程,但沒有得到它。我使用網址在我的網站上嵌入了視頻,並且我有一個拉動縮略圖的功能,我只是想要類似的東西來獲得持續時間。以下是我得到了大拇指......從YouTube獲取持續時間url

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; 

}

回答

11

你可以使用這樣的事情:

<?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'); 

?> 

返回視頻秒的持續時間。

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

您可以使用像this one功能到秒改爲小時,分鐘和秒。

+0

我需要$ video_id將它從輸入到每個帖子的自定義字段中的url中拉出來。 – 2012-02-06 21:52:13

+0

更新了示例以從url獲取video_id – stewe 2012-02-06 22:02:40

+0

我將此用作函數,它可以工作,但是如果視頻已從YouTube上刪除,那麼我會在嘗試輸出時遇到錯誤。我怎樣才能做出一個if語句來防止這種情況發生呢? – 2012-02-06 23:07:46

0

您可以簡單地使用time formater將秒數轉換爲您喜歡的任何格式。 即返回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

此端點(v2)不再有效。 – 2017-04-04 11:45:40

3

的YouTube API V3


使用

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

功能

/** 
* 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

不適合我,說file_get_content由於安全原因被阻止 – 2017-06-13 13:50:40

1

這是我的函數來獲得youtube持續時間秒。 他完全是100%的工作。 你只需要youtube id video和youtube api key。

如何添加YouTube的API密鑰顯示 這個視頻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; 

    } 

這是我函數獲取第二YouTube的持續時間。 他完全是100%的工作。 你只需要youtube id video和youtube api key。

如何添加YouTube的API密鑰顯示 這個視頻https://www.youtube.com/watch?v=4AQ9UamPN6E

0

1)您將需要一個API密鑰。如有必要,請轉至https://developers.google.com/並登錄或創建一個帳戶。登錄後,轉到此鏈接https://console.developers.google.com/project並單擊藍色的CREATE PROJECT按鈕。 Google等待您的項目準備就緒。

2)您將需要一個運行PHP且支持file_get_content的Web主機。你可以通過創建一個新的腳本來檢查,只需「echo php_info();」並驗證allow_url_fopen設置爲On。如果不是,則更改配置或與您的虛擬主機交談。

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

希望這有助於!