worklet-recorder.js (1712B)
1 /** 2 * @class RecorderProcessor 3 * @extends AudioWorkletProcessor 4 * 5 * A simple recorder AudioWorkletProcessor. Returns the recorded buffer to the 6 * node when recording is finished. 7 */ 8 class RecorderProcessor extends AudioWorkletProcessor { 9 /** 10 * @param {*} options 11 * @param {number} options.duration A duration to record in seconds. 12 * @param {number} options.channelCount A channel count to record. 13 */ 14 constructor(options) { 15 super(); 16 this._createdAt = currentTime; 17 this._elapsed = 0; 18 this._recordDuration = options.duration || 1; 19 this._recordChannelCount = options.channelCount || 1; 20 this._recordBufferLength = sampleRate * this._recordDuration; 21 this._recordBuffer = []; 22 for (let i = 0; i < this._recordChannelCount; ++i) { 23 this._recordBuffer[i] = new Float32Array(this._recordBufferLength); 24 } 25 } 26 27 process(inputs, outputs) { 28 if (this._recordBufferLength <= currentFrame) { 29 this.port.postMessage({ 30 type: 'recordfinished', 31 recordBuffer: this._recordBuffer 32 }); 33 this.port.close(); 34 return false; 35 } 36 37 // Records the incoming data from |inputs| and also bypasses the data to 38 // |outputs|. 39 const input = inputs[0]; 40 const output = outputs[0]; 41 for (let channel = 0; channel < input.length; ++channel) { 42 const inputChannel = input[channel]; 43 const outputChannel = output[channel]; 44 outputChannel.set(inputChannel); 45 46 const buffer = this._recordBuffer[channel]; 47 const capacity = buffer.length - currentFrame; 48 buffer.set(inputChannel.slice(0, capacity), currentFrame); 49 } 50 51 return true; 52 } 53 } 54 55 registerProcessor('recorder-processor', RecorderProcessor);