Skip to content

Instantly share code, notes, and snippets.

@trujic1000
Created May 6, 2025 16:49
Show Gist options
  • Save trujic1000/4e50598135c8e39b3709734cb5ecd193 to your computer and use it in GitHub Desktop.
Save trujic1000/4e50598135c8e39b3709734cb5ecd193 to your computer and use it in GitHub Desktop.
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