Skip to content

Instantly share code, notes, and snippets.

@pylixonly
Created December 27, 2022 07:55
Show Gist options
  • Save pylixonly/df33e224fef70ee1cbed464accb1dbdf to your computer and use it in GitHub Desktop.
Save pylixonly/df33e224fef70ee1cbed464accb1dbdf to your computer and use it in GitHub Desktop.
Get the duration of a Youtube video
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