92 lines
2 KiB
TypeScript
92 lines
2 KiB
TypeScript
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
const portAudio = require('naudiodon');
|
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
const { Writable } = require('stream');
|
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
const { StringDecoder } = require('string_decoder');
|
|
|
|
interface RecorderI {
|
|
stop(): string;
|
|
pause(): void;
|
|
}
|
|
|
|
type inputOptions = {
|
|
channelCount: number;
|
|
sampleFormat: number;
|
|
sampleRate: number;
|
|
deviceId: number;
|
|
closeOnError: boolean;
|
|
}
|
|
|
|
class StringWritable extends Writable {
|
|
|
|
constructor(options: {
|
|
defaultEncoding: string;
|
|
}) {
|
|
super(options);
|
|
this._decoder = new StringDecoder(options && options.defaultEncoding);
|
|
this.data = '';
|
|
}
|
|
|
|
_write(chunk: Buffer, encoding: string, callback: (error? : Error) => void) {
|
|
if (encoding === 'buffer') {
|
|
chunk = this._decoder.write(chunk);
|
|
}
|
|
this.data += chunk;
|
|
console.log('writing');
|
|
callback();
|
|
}
|
|
|
|
_final(callback: (error? : Error) => void) {
|
|
console.log('yayayay');
|
|
this.data += this._decoder.end();
|
|
callback();
|
|
}
|
|
}
|
|
|
|
export class Recorder implements RecorderI {
|
|
|
|
private ia: any;
|
|
private micWritable: StringWritable;
|
|
private recorderOptions: inputOptions;
|
|
|
|
constructor(options: inputOptions, encoding: string) {
|
|
this.recorderOptions = options;
|
|
this.micWritable = new StringWritable({
|
|
defaultEncoding: encoding
|
|
});
|
|
try {
|
|
this.start();
|
|
} catch(e) {
|
|
console.log('RECORDER ERROR!', e);
|
|
}
|
|
}
|
|
|
|
private start(): void {
|
|
this.ia = new portAudio.AudioIO({
|
|
inOptions: this.recorderOptions
|
|
});
|
|
this.ia.pipe(this.micWritable);
|
|
this.ia.start();
|
|
this.pause();
|
|
}
|
|
|
|
pause(): void {
|
|
this.ia.pause();
|
|
}
|
|
|
|
resume(){
|
|
this.ia.resume();
|
|
}
|
|
|
|
getData(): string {
|
|
const data = this.micWritable.data;
|
|
this.micWritable.data = '';
|
|
return data;
|
|
}
|
|
|
|
stop(): string {
|
|
this.ia.quit();
|
|
return this.getData();
|
|
}
|
|
}
|