46 lines
1.9 KiB
JavaScript
46 lines
1.9 KiB
JavaScript
// A 10 ms speech-band level and a high-frequency level. The worklet sends
|
|
// these features to the page. Raw input never leaves the worklet on this port.
|
|
export class SpeechEnvelope {
|
|
constructor(rate, emit) {
|
|
this.rate = rate;
|
|
this.emit = emit;
|
|
this.lowCoeff = 1 - Math.exp(-2 * Math.PI * 150 / rate);
|
|
this.highCoeff = 1 - Math.exp(-2 * Math.PI * 1600 / rate);
|
|
this.low = this.high = this.energy = this.highEnergy = 0;
|
|
this.frames = this.count = 0;
|
|
this.next = Math.round(rate / 100);
|
|
this.bin = 0;
|
|
this.present = true;
|
|
}
|
|
push(samples, length) {
|
|
for (let i = 0; i < length; i++) {
|
|
const x = samples?.[i] ?? 0;
|
|
this.present &&= i < (samples?.length ?? 0);
|
|
this.low += this.lowCoeff * (x - this.low);
|
|
this.high += this.highCoeff * (x - this.high);
|
|
this.energy += (x - this.low) ** 2;
|
|
this.highEnergy += (x - this.high) ** 2;
|
|
this.count++;
|
|
if (++this.frames < this.next) continue;
|
|
const db = e => 10 * Math.log10(Math.max(1e-10, e / this.count));
|
|
this.emit(db(this.energy), db(this.highEnergy), this.present);
|
|
this.energy = this.highEnergy = this.count = 0;
|
|
this.present = true;
|
|
this.next = Math.round((++this.bin + 1) * this.rate / 100);
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function speechBuffer(context) {
|
|
const response = await fetch('speech-reference.flac');
|
|
if (!response.ok) throw Error('Speech reference unavailable');
|
|
return context.decodeAudioData(await response.arrayBuffer());
|
|
}
|
|
|
|
export function referenceFeatures(samples, rate) {
|
|
const levels = [], highs = [];
|
|
const envelope = new SpeechEnvelope(rate, (level, high) => { levels.push(level); highs.push(high); });
|
|
envelope.push(samples, samples.length);
|
|
return {levels, highs};
|
|
}
|