Get duration from a youtube url

前端 未结 6 1058
感情败类
感情败类 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 10:59

    This is my function to get youtube duration in second. he is fully 100% work. you need just youtube id video and youtube api key.

    how to add youtube api key show this video 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;
    
        }
    

    This is my function to get youtube duration in second. he is fully 100% work. you need just youtube id video and youtube api key.

    how to add youtube api key show this video https://www.youtube.com/watch?v=4AQ9UamPN6E

    0 讨论(0)
  • You could use something like this:

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

    that returns the duration in seconds of the video.

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

    You can use a function like this one to change the seconds to hours, minutes, and seconds.

    0 讨论(0)
  • 2021-02-08 11:10

    You can simply use a time formater to change the seconds into whatever format you like. i.e. return gmdate("H:i:s", $obj->data->duration);

    0 讨论(0)
  • 2021-02-08 11:10

    1) You will need an API key. Go to https://developers.google.com/ and log in or create an account, if necessary. After logging in go to this link https://console.developers.google.com/project and click on the blue CREATE PROJECT button. Wait a moment as Google prepares your project.

    2) You will need a web host that is running PHP with file_get_content supported. You can check by creating a new script with just "echo php_info();" and verifying that allow_url_fopen is set to On. If it is not, then change the configuration or talk to your web host.

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

    Hope this helps!

    0 讨论(0)
  • 2021-02-08 11:15
    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");
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题