Files
baji-vc/gateway/web/capture-worklet.js

18 lines
994 B
JavaScript

import {Resampler} from './audio-core.js';
class Capture extends AudioWorkletProcessor {
constructor(){super();this.resampler=new Resampler(sampleRate,16000);this.pending=[];this.enabled=false;this.total=0;
this.port.onmessage=({data})=>{this.enabled=data.enabled;this.pending=[];this.resampler=new Resampler(sampleRate,16000);this.total=0;};
}
process(inputs,outputs){
const audio=inputs[0]?.[0];
if(audio){let energy=0;for(const x of audio)energy+=x*x;
if(this.enabled){
this.pending.push(...this.resampler.push(audio));
while(this.pending.length>=320){const frame=new Int16Array(320);for(let i=0;i<320;i++)frame[i]=Math.round(Math.max(-1,Math.min(1,this.pending[i]))*32767);this.pending.splice(0,320);this.total+=320;this.port.postMessage({type:'frame',pcm:frame.buffer,endSample:this.total,rms:Math.sqrt(energy/audio.length),captureContextTime:currentTime},[frame.buffer]);}
}
}
return true;
}
}
registerProcessor('capture',Capture);