从youtube网址获取持续时间

Pol*_*fra 9 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;
Run Code Online (Sandbox Code Playgroud)

}

ste*_*ewe 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');

?>
Run Code Online (Sandbox Code Playgroud)

返回视频的持续时间(以秒为单位).

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

您可以使用类似这样的函数将秒数更改为小时,分钟和秒.


Man*_*s D 5

youtube api v3


用法

echo youtubeVideoDuration('video_url', 'your_api_key');
// output: 63 (seconds)
Run Code Online (Sandbox Code Playgroud)

功能

/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)