Created
December 27, 2022 07:55
-
-
Save pylixonly/df33e224fef70ee1cbed464accb1dbdf to your computer and use it in GitHub Desktop.
Get the duration of a Youtube video
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async getDuration(videoId: string): Promise<number> { | |
console.log(`Fetching duration for ${videoId}..`); | |
const video = await fetch(`${this.apiUrl}/videos?part=contentDetails&id=${videoId}`); // add api key params here as well | |
// get the first result | |
const [videoResult] = await video.json().then(x => x.items); | |
console.log(`Duration for ${videoId} is ${videoResult.contentDetails.duration}`); | |
// convert to seconds | |
return this.convertToSeconds(videoResult.contentDetails.duration); | |
} | |
convertToSeconds(duration): number { | |
let match = duration | |
.match(/PT(\d+H)?(\d+M)?(\d+S)?/) | |
.slice(1) | |
.map((x: string) => x?.replace(/\D/, '')); | |
return ( | |
(Number(match[0]) || 0) * 3600 + | |
(Number(match[1]) || 0) * 60 + | |
(Number(match[2]) || 0) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment