Created
May 6, 2025 16:49
-
-
Save trujic1000/4e50598135c8e39b3709734cb5ecd193 to your computer and use it in GitHub Desktop.
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
import { createWriteStream, unlink } from 'fs'; | |
import { promisify } from 'util'; | |
import ffprobeStatic from 'ffprobe-static'; | |
import { getAudioDurationInSeconds } from 'get-audio-duration'; | |
import { v4 as uuid } from 'uuid'; | |
import { finished } from 'stream/promises'; | |
const unlinkAsync = promisify(unlink); | |
export const getDurationFromStream = async (stream) => { | |
if (!stream) return null; | |
const fileName = `temp-${uuid()}.mp3`; | |
const fileStream = createWriteStream(fileName); | |
try { | |
await finished(stream.pipe(fileStream)); // Wait until stream is fully written | |
const duration = await getAudioDurationInSeconds(fileName, ffprobeStatic.path); | |
return duration; | |
} catch (err) { | |
console.error('Failed to get duration:', err); | |
return null; | |
} finally { | |
try { | |
await unlinkAsync(fileName); // Always clean up | |
} catch (e) { | |
console.warn(`Failed to delete temp file: ${fileName}`, e); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment