2011-10-14 137 views
4

我遇到問題。如何獲得YouTube視頻的持續時間? 這是場景。獲取YouTube視頻文件的時間長度

我在這個領域的輸入字段說我輸入YouTube網址現在我想 把驗證該視頻應該只是1分鐘,如果是的話,我 這些信息存儲在數據庫一樣,我顯示錯誤信息。

是否可以做這件事?

回答

4

按照他們的文檔,In a video feed entry, the <yt:duration> tag specifies a video's length.

+0

但我只有視頻的網址... – theGame

+0

使用網址和數據API(http://code.google.com/apis/youtube/overview.html),您將獲得以上信息 – Ktash

0

視頻的網址將包含視頻ID。使用YouTube's API請求視頻信息時,您可以使用此ID。在視頻反饋中,您應該有一個<yt:duration>標籤,您可以使用它來獲取視頻的持續時間。只需稍微介紹一下API,你就可以找到你需要的東西。

5

您可以使用數據API來獲取視頻的信息。您可能需要從網址中提取視頻的標識符。

http://code.google.com/apis/youtube/2.0/developers_guide_php.html#Retrieving_Video_Entry

如果你使用Zend,不過已經有了類做繁重:

<?php 
require_once 'Zend/Loader.php'; // the Zend dir must be in your include_path 
Zend_Loader::loadClass('Zend_Gdata_YouTube'); 
$yt = new Zend_Gdata_YouTube(); 
$videoEntry = $yt->getVideoEntry('the0KZLEacs'); 
$duration = $videoEntry->getVideoDuration(); 

如果沒有,你可以去http://gdata.youtube.com/feeds/api/videos/{$videoId},並得到一個XML文檔來處理自己。

例如,http://gdata.youtube.com/feeds/api/videos/KURI9EQV3dY返回XML文檔包含包括持續時間信息的視頻:​​

+0

不幸的是,使用來自youtube.com的'gdata.youtube.com'贏得了' (至少對於用戶腳本而言),因爲Chrome將其封鎖爲「不安全」 - 即使它們是他們自己的域名。 ': - /' – Synetech

1

下面的代碼將讓你的視頻縮略圖,標題和持續時間,從URL。只需從最後更改YouTube鏈接。

演示:http://100ro.ro/wp-includes/ajaxdemo/test.php?y=www.youtube.com/watch?v=V80jm1rs2UQ

注:使用YouTube網址在Y = youtubeurl不包含http://

<?php 

     getYoutubeImage($_GET["y"]); 

      function getYoutubeImage($e){ 
      //GET THE URL 
      $url = $e; 

      $queryString = parse_url($url, PHP_URL_QUERY); 

      parse_str($queryString, $params); 

      $v = $params['v']; 




     // function to parse a video <entry> 
     function parseVideoEntry($entry) {  
      $obj= new stdClass; 

      // get nodes in media: namespace for media information 
      $media = $entry->children('http://search.yahoo.com/mrss/'); 
      $obj->title = $media->group->title; 
      $obj->description = $media->group->description; 



      // get <yt:duration> node for video length 
      $yt = $media->children('http://gdata.youtube.com/schemas/2007'); 
      $attrs = $yt->duration->attributes(); 
      $obj->length = $attrs['seconds']; 


      // return object to caller 
      return $obj;  
     } 

     // get video ID from $_GET 
     if (!isset($v)) { 
      die ('ERROR: Missing video ID'); 
     } else { 
      $vid = $v; 
     } 

     // set video data feed URL 
     $feedURL = 'http://gdata.youtube.com/feeds/api/videos/' . $v; 

     // read feed into SimpleXML object 
     $entry = simplexml_load_file($feedURL); 

     // parse video entry 
     $video = parseVideoEntry($entry); 

     // display video image, title and duration 
     echo "<img src='http://i3.ytimg.com/vi/$v/default.jpg' width='150' />"; 
     echo "<p>{$video->title}</p>"; 
     echo "<p>".sprintf("%0.2f", $video->length/60) . " min. </p>"; 


     } 

     ?>