如何获得YouTube视频持续时间?

问题描述 投票:3回答:3

所以我想获取YouTube视频的持续时间。我找到了一些解决方案,但其中大多数已经过时了。我实际尝试过的内容:

public function getYTdata($url){
    $youtube = "http://www.youtube.com/oembed?url=". $url ."&format=json";

    $curl = curl_init($youtube);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $return = curl_exec($curl);
    curl_close($curl);
    return json_decode($return, true);
}

输出:

{"thumbnail_url":"https:\/\/i.ytimg.com\/vi\/jmQsk6tm5aY\/hqdefault.jpg","provider_url":"https:\/\/www.youtube.com\/","thumbnail_height":360,"type":"video","provider_name":"YouTube","version":"1.0","html":"<iframe width=\"480\" height=\"270\" src=\"https:\/\/www.youtube.com\/embed\/jmQsk6tm5aY?feature=oembed\" frameborder=\"0\" gesture=\"media\" allow=\"encrypted-media\" allowfullscreen><\/iframe>","author_name":"Trap Nation","width":480,"title":"Evalyn - Filthy Rich (Sweater Beats Remix)","height":270,"thumbnail_width":480,"author_url":"https:\/\/www.youtube.com\/user\/AllTrapNation"}

我的方法未显示持续时间。那么如何获得youtube视频的持续时间?

php laravel
3个回答
1
投票

好的,我找到了解决方法:

public function getYoutubeDuration($vid) {
    //$vid - YouTube video ID. F.e. LWn28sKDWXo
    $videoDetails = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=".$vid."&part=contentDetails,statistics&key=YOUR_KEY");
    $VidDuration = json_decode($videoDetails, true);
    foreach ($VidDuration['items'] as $vidTime)
    {
      $VidDuration= $vidTime['contentDetails']['duration'];
    }
    $pattern='/PT(\d+)M(\d+)S/';
    preg_match($pattern,$VidDuration,$matches);
    $seconds=$matches[1]*60+$matches[2];
    return $seconds;
}

0
投票
function YoutubeVideoInfo($video_id) {

        $url = 'https://www.googleapis.com/youtube/v3/videos?id='.$video_id.'&key=AIzaSyDYwPzLevXauI-kTSVXTLroLyHEONuF9Rw&part=snippet,contentDetails';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $response = curl_exec($ch);
        curl_close($ch);
        $response_a = json_decode($response);
        //print_t($response_a); if you want to get all video details
        return  $response_a->items[0]->contentDetails->duration; //get video duaration
      }
 //passing youtube videoId to function 
 YoutubeVideoInfo('DDtDRFvB49M');

0
投票

正则表达式'/ PT(\ d +)M(\ d +)S /'不足以涵盖YouTube时间格式的所有情况。

您还需要:

/PT(\d+)H(\d+)M(\d+)S/
/PT(\d+)M/
/PT(\d+)S/

最好将它们组合成一个OR-ed表达式,从最长到最短排序。

© www.soinside.com 2019 - 2024. All rights reserved.