Spaces:
Running
Running
Download audio.js from Cis-Labs/forced-aligner: direct link, hf CLI and curl.
- Browser
- Download file 2.39 kB
-
https://huggingface.co/spaces/Cis-Labs/forced-aligner/resolve/main/audio.js
- Command line
-
hf download hf://spaces/Cis-Labs/forced-aligner/audio.js
-
curl -L -o audio.js https://huggingface.co/spaces/Cis-Labs/forced-aligner/resolve/main/audio.js
2.39 kB
| // Audio decoding for the page: any format the browser can play, to 16 kHz mono float32. | |
| import { SAMPLE_RATE } from "./aligner.js"; | |
| /** | |
| * Decode an encoded file (ArrayBuffer) to 16 kHz mono. The browser's decoder resamples to the | |
| * context rate; channels are averaged, as in aligner.py. | |
| * @returns {Promise<{wav: Float32Array, duration: number, sourceRate: number, channels: number}>} | |
| */ | |
| export async function decodeAudio(arrayBuffer, maxSeconds = Infinity) { | |
| let buf; | |
| try { | |
| const ctx = new OfflineAudioContext(1, 1, SAMPLE_RATE); | |
| buf = await ctx.decodeAudioData(arrayBuffer.slice(0)); | |
| } catch { | |
| buf = null; // some browsers only decode at their native rate; resample below | |
| } | |
| if (!buf) { | |
| const AC = globalThis.AudioContext || globalThis.webkitAudioContext; | |
| if (!AC) throw new Error("This browser cannot decode audio (no Web Audio API)."); | |
| const ac = new AC(); | |
| try { | |
| buf = await ac.decodeAudioData(arrayBuffer.slice(0)); | |
| } catch { | |
| throw new Error("Could not decode this audio file. Try WAV, FLAC, MP3, OGG or M4A."); | |
| } finally { | |
| ac.close?.(); | |
| } | |
| } | |
| if (buf.duration > maxSeconds + 0.5) { | |
| const err = new Error(tooLong(buf.duration, maxSeconds)); | |
| err.user = true; | |
| throw err; | |
| } | |
| if (buf.sampleRate !== SAMPLE_RATE) buf = await resample(buf); | |
| const n = buf.length; | |
| const wav = new Float32Array(n); | |
| for (let c = 0; c < buf.numberOfChannels; c++) { | |
| const ch = buf.getChannelData(c); | |
| for (let i = 0; i < n; i++) wav[i] += ch[i]; | |
| } | |
| if (buf.numberOfChannels > 1) for (let i = 0; i < n; i++) wav[i] /= buf.numberOfChannels; | |
| if (!n) throw new Error("The audio file contains no samples."); | |
| return { wav, duration: n / SAMPLE_RATE, sourceRate: buf.sampleRate, channels: buf.numberOfChannels }; | |
| } | |
| async function resample(buf) { | |
| const len = Math.ceil((buf.length * SAMPLE_RATE) / buf.sampleRate); | |
| const off = new OfflineAudioContext(buf.numberOfChannels, len, SAMPLE_RATE); | |
| const src = off.createBufferSource(); | |
| src.buffer = buf; | |
| src.connect(off.destination); | |
| src.start(); | |
| return off.startRendering(); | |
| } | |
| export function tooLong(duration, maxSeconds) { | |
| return `The audio is ${(duration / 60).toFixed(1)} min long; this demo aligns up to ` + | |
| `${Math.round(maxSeconds / 60)} min. Run the same model locally for longer files ` + | |
| "(see 'Use it in your pipeline')."; | |
| } | |