Skip to content

Instantly share code, notes, and snippets.

@zoolu-got-rhythm
Created September 8, 2023 22:03
Show Gist options
  • Save zoolu-got-rhythm/c05d0abc177a373cd1608c148d4a041e to your computer and use it in GitHub Desktop.
Save zoolu-got-rhythm/c05d0abc177a373cd1608c148d4a041e to your computer and use it in GitHub Desktop.
get the length/duration (in milliseconds) of an audio file in JS, written in TS
/**
* returns a promise which when resolves returns the duration of the audio in milliseconds or
* rejects with the value if something goes wrong
*/
export function getDurationOfAudioInMilliseconds(src: string): Promise<number> {
return new Promise((resolve, reject) => {
var audio = new Audio();
audio.addEventListener("loadedmetadata", function () {
if (audio.duration) {
resolve(audio.duration * 1000);
} else {
reject(audio.duration);
}
});
audio.src = src;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment