32 lines
1.7 KiB
JavaScript
32 lines
1.7 KiB
JavaScript
const RATE = 16000;
|
|
|
|
export class AudioPreprocessor {
|
|
static async prepare(file, { signal } = {}) {
|
|
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
console.log("[BoomCast][YAMNet] Preparing local classification.");
|
|
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
|
|
if (!AudioContextClass || !(window.OfflineAudioContext || window.webkitOfflineAudioContext)) throw new Error("Browser audio decoding unavailable");
|
|
const context = new AudioContextClass();
|
|
try {
|
|
const decoded = await context.decodeAudioData(await file.arrayBuffer());
|
|
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
if (!decoded.duration || !Number.isFinite(decoded.duration)) throw new Error("Invalid audio duration");
|
|
const OfflineContextClass = window.OfflineAudioContext || window.webkitOfflineAudioContext;
|
|
const offline = new OfflineContextClass(1, Math.ceil(decoded.duration * RATE), RATE);
|
|
const source = offline.createBufferSource();
|
|
source.buffer = decoded;
|
|
source.connect(offline.destination);
|
|
source.start();
|
|
const rendered = await offline.startRendering();
|
|
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
const waveform = rendered.getChannelData(0).slice();
|
|
console.log("[BoomCast][YAMNet] Waveform prepared.", {
|
|
sampleRate: RATE, samples: waveform.length, durationSeconds: waveform.length / RATE,
|
|
});
|
|
return waveform;
|
|
} finally {
|
|
await context.close().catch(() => {});
|
|
}
|
|
}
|
|
}
|