Created
September 8, 2023 22:03
-
-
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
This file contains 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
/** | |
* 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