42 lines
919 B
TypeScript
42 lines
919 B
TypeScript
import fs from "node:fs/promises"
|
|
import * as music from "music-metadata"
|
|
|
|
const MAX_ENTRIES = 1000
|
|
|
|
export type AudioInfo = {
|
|
codec: string | undefined
|
|
duration: number | undefined
|
|
}
|
|
|
|
const cache = new Map<string, Promise<AudioInfo>>()
|
|
|
|
/** Codec info for a file, parsed once per file version. */
|
|
export async function audioInfo(file: string): Promise<AudioInfo> {
|
|
const stat = await fs.stat(file)
|
|
const key = `${file}\0${stat.size}\0${stat.mtimeMs}`
|
|
|
|
const cached = cache.get(key)
|
|
if (cached) {
|
|
cache.delete(key)
|
|
cache.set(key, cached)
|
|
return cached
|
|
}
|
|
|
|
const info = music.parseFile(file).then(({ format }) => ({
|
|
codec: format.codec,
|
|
duration: format.duration,
|
|
}))
|
|
cache.set(key, info)
|
|
info.catch(() => {
|
|
if (cache.get(key) === info) {
|
|
cache.delete(key)
|
|
}
|
|
})
|
|
|
|
if (cache.size > MAX_ENTRIES) {
|
|
cache.delete(cache.keys().next().value!)
|
|
}
|
|
|
|
return info
|
|
}
|