UNPKG

recorder-audio-worklet-processor

Version:

The AudioWorkletProcessor which is used by the recorder-audio-worklet package.

104 lines 3.79 kB
export class RecorderAudioWorkletProcessor extends AudioWorkletProcessor { constructor() { super(); this._encoderPort = null; this._numberOfChannels = 0; this._state = 'inactive'; this.port.onmessage = ({ data }) => { if (data.method === 'pause') { if (this._state === 'active' || this._state === 'recording') { this._state = 'paused'; this._sendAcknowledgement(data.id); } else { this._sendUnexpectedStateError(data.id); } } else if (data.method === 'record') { if (this._state === 'inactive') { this._encoderPort = data.params.encoderPort; this._state = 'active'; this._sendAcknowledgement(data.id); } else { this._sendUnexpectedStateError(data.id); } } else if (data.method === 'resume') { if (this._state === 'paused') { this._state = 'active'; this._sendAcknowledgement(data.id); } else { this._sendUnexpectedStateError(data.id); } } else if (data.method === 'stop') { if ((this._state === 'active' || this._state === 'paused' || this._state === 'recording') && this._encoderPort !== null) { this._stop(this._encoderPort); this._sendAcknowledgement(data.id); } else { this._sendUnexpectedStateError(data.id); } } else if (typeof data.id === 'number') { this.port.postMessage({ error: { code: -32601, message: 'The requested method is not supported.' }, id: data.id }); } }; } process([input]) { if (this._state === 'inactive' || this._state === 'paused') { return true; } if (this._state === 'active') { if (input === undefined) { throw new Error('No channelData was received for the first input.'); } if (input.length === 0) { return true; } this._state = 'recording'; } if (this._state === 'recording' && this._encoderPort !== null) { if (input === undefined) { throw new Error('No channelData was received for the first input.'); } if (input.length === 0) { this._encoderPort.postMessage(Array.from({ length: this._numberOfChannels }, () => 128)); } else { this._encoderPort.postMessage(input, input.map(({ buffer }) => buffer)); this._numberOfChannels = input.length; } return true; } return false; } _sendAcknowledgement(id) { this.port.postMessage({ id, result: null }); } _sendUnexpectedStateError(id) { this.port.postMessage({ error: { code: -32603, message: 'The internal state does not allow to process the given message.' }, id }); } _stop(encoderPort) { encoderPort.postMessage([]); encoderPort.close(); this._encoderPort = null; this._state = 'stopped'; } } RecorderAudioWorkletProcessor.parameterDescriptors = []; //# sourceMappingURL=recorder-audio-worklet-processor.js.map