从youtube网址获取持续时间

时间:2012-02-06 21:21:44

标签: youtube meta

我正在寻找能够从网址中提取视频的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;

}

6 个答案:

答案 0 :(得分:13)

您可以使用以下内容:

<?php

    function getDuration($url){

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


        $data=@file_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之类的功能将秒数更改为小时,分钟和秒。

答案 1 :(得分:4)

youtube api v3

<强>使用

<div id="wrapper">
    <div class="navbar-default sidebar" role="navigation">
        <div class="sidebar-nav navbar-collapse collapse"> 
            <ul class="nav" id="side-menu">    
                <li>
                    <a class="active" href="#"><i class="fa fa-bar-chart-o fa-fw"></i> Operation <span class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">               
                        <li>
                            <a href="#"><i class="fa fa-bar-chart-o fa-fw"> </i> Request<span class="fa arrow"></span></a>  
                            <ul class="nav nav-third-level">                                        
                                <li>
                                    <a href="<%: Url.Action("ListItems", "Request") %>"><i class="fa fa-dashboard fa-fw"></i> Browse</a>
                                </li>
                                <li>
                                    <a href="<%: Url.Action("EditItem", "Request") %>"><i class="fa fa-dashboard fa-fw"></i> Add</a>
                                </li> 
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</div> 

<强>功能

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

答案 2 :(得分:3)

这是我的功能,以获得youtube持续时间秒。 他完全100%的工作。 你只需要youtube id视频和youtube api密钥。

如何添加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视频和youtube api密钥。

如何添加youtube api键显示 这个视频https://www.youtube.com/watch?v=4AQ9UamPN6E

答案 3 :(得分:0)

您可以简单地使用时间格式器将秒数更改为您喜欢的任何格式。 一世。 return gmdate(“H:i:s”,$ obj-&gt; data-&gt; duration);

答案 4 :(得分: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");

答案 5 :(得分:0)

1)您需要一个API密钥。如有必要,请转到https://developers.google.com/并登录或创建帐户。登录后,转到此链接https://console.developers.google.com/project,然后单击蓝色的CREATE PROJECT按钮。等待Google准备您的项目。

2)您将需要一个运行PHP并且支持file_get_content的Web主机。您只需使用&#34; echo php_info();&#34;创建一个新脚本即可进行检查。并验证allow_url_fopen是否设置为On。如果不是,则更改配置或与您的Web主机通话。

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

希望这有帮助!