Get duration from a youtube url

前端 未结 6 1061
感情败类
感情败类 2021-02-08 10:51

Im looking for a function that will pull the youtube duration of a video from the url. I read some tutorials but don\'t get it. I embed videos on my site using a url and I have

6条回答
  •  迷失自我
    2021-02-08 11:19

    youtube api v3


    usage

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

    function

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

提交回复
热议问题