Skip to content

🎥 Make videos programmatically with React

Update get-audio-duration.ts

Jonny Burgerfdc78c41ad10
diff --git a/packages/media-utils/src/get-audio-duration.ts b/packages/media-utils/src/get-audio-duration.ts
index 20ab7eaa3b..49df8ab8e9 100644
--- a/packages/media-utils/src/get-audio-duration.ts
+++ b/packages/media-utils/src/get-audio-duration.ts
@@ -1,10 +1,14 @@
-/**
- * Get the audio file passed in parameter duration in seconds
- * @async
- * @param src path to the audio file
- * @return {number} duration of the audio file in seconds
- */
-export const getAudioDurationInSeconds = (src: string): Promise<number> => {
+import {pLimit} from './p-limit';
+
+const limit = pLimit(3);
+
+const metadataCache: {[key: string]: number} = {};
+
+const fn = (src: string): Promise<number> => {
+ if (metadataCache[src]) {
+ return Promise.resolve(metadataCache[src]);
+ }
+
const audio = document.createElement('audio');
audio.src = src;
return new Promise<number>((resolve, reject) => {
@@ -14,6 +18,7 @@ export const getAudioDurationInSeconds = (src: string): Promise<number> => {
};
const onLoadedMetadata = () => {
+ metadataCache[src] = audio.duration;
resolve(audio.duration);
cleanup();
};
@@ -21,6 +26,7 @@ export const getAudioDurationInSeconds = (src: string): Promise<number> => {
const cleanup = () => {
audio.removeEventListener('loadedmetadata', onLoadedMetadata);
audio.removeEventListener('error', onError);
+ audio.remove();
};
audio.addEventListener('loadedmetadata', onLoadedMetadata, {once: true});
@@ -28,6 +34,16 @@ export const getAudioDurationInSeconds = (src: string): Promise<number> => {
});
};
+/**
+ * Get the audio file passed in parameter duration in seconds
+ * @async
+ * @param src path to the audio file
+ * @return {number} duration of the audio file in seconds
+ */
+export const getAudioDurationInSeconds = (src: string) => {
+ return limit(fn, src);
+};
+
/**
* @deprecated Renamed to `getAudioDurationInSeconds`
*/