Is it possible to get the duration (time) video through Youtube data API v3.0

Is it possible to get the duration (time) video through Youtube data API v3.0. If so, how?

Upvotes: 0

Views: 5605

Answers (3)

Sanusi hassan
Sanusi hassan

Reputation: 301

using javascript

function converTime(d) {
  //ignore the "PT" part
  d = d.search(/PT/i) > -1? d.slice(2) : d;
  let h, m, s;
  //indexes of the letters h, m, s in the duration
  let hIndex = d.search(/h/i),
      mIndex = d.search(/m/i),
      sIndex = d.search(/s/i);
  //is h, m, s inside the duration
  let dContainsH = hIndex > -1,
      dContainsM = mIndex > -1,
      dContainsS = sIndex > -1;
  //setting h, m, s
  h = dContainsH? d.slice(0, hIndex) + ":" : "";
  m = dContainsM? d.slice(dContainsH ? hIndex + 1 : 0, mIndex) : dContainsH? "0" : "0";
  s = dContainsS? d.slice(dContainsM ? mIndex + 1 : hIndex + 1, sIndex) : "0";
  //adding 0 before m or s
  s = (dContainsM || dContainsS) && s < 10? "0" + s: s;
  m = (dContainsH || dContainsM) && m < 10? "0" + m + ":" : m + ":";
  return d !== "0S" ? h + m + s : "LIVE"
}
console.log(converTime("PT6M7S"));

Upvotes: 1

Meryan
Meryan

Reputation: 1473

Here is how I did it from .NET and C#.
First include the "contentDetails" part

var searchListRequest = youtubeService.Videos.List("snippet,contentDetails");

Second convert the duration to something more programmatically manageable as follows:

TimeSpan YouTubeDuration = System.Xml.XmlConvert.ToTimeSpan(searchResult.ContentDetails.Duration);

I hope this is helpful

Upvotes: 1

unrealsoul007
unrealsoul007

Reputation: 4077

You will have to make a call to the Youtube Data API's Video resource after you make the search call. You can put up to 50 video id's in search, so you wont have to call it for each element.

https://developers.google.com/youtube/v3/docs/videos/list

You'll want to set part=contentDetails, because duration is there.

For example the following call:

https://www.googleapis.com/youtube/v3/videos?id=9bZkp7q19f0&part=contentDetails&key={YOUR_API_KEY}

Gives this result:

{
 "kind": "youtube#videoListResponse",
 "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/ny1S4th-ku477VARrY_U4tIqcTw\"",
 "items": [
  {

   "id": "9bZkp7q19f0",
   "kind": "youtube#video",
   "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/HN8ILnw-DBXyCcTsc7JG0z51BGg\"",
   "contentDetails": {
    "duration": "PT4M13S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "false",
    "licensedContent": true,
    "regionRestriction": {
     "blocked": [
      "DE"
     ]
    }
   }
  }
 ]
}

The time is formatted as an ISO 8601 string. PT stands for Time Duration, 4M is 4 minutes, and 13S is 13 seconds.

Please refer to this question for more details

Upvotes: 2

Related Questions