Skip to content

Instantly share code, notes, and snippets.

@nicolaspanel
Created August 24, 2016 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nicolaspanel/c05a6a1a81ac0207a869ee7ca930c573 to your computer and use it in GitHub Desktop.
Save nicolaspanel/c05a6a1a81ac0207a869ee7ca930c573 to your computer and use it in GitHub Desktop.
basic microphone for nodejs (linux)

Requirements

  • arecord: sudo apt-get install alsa-utils
  • lodash: npm install lodash

Usage

const Microphone =  require('./path/to/microphone');
const mic = new Microphone();
mic.pipe(someWritable);
setTimeout(() => mic.stop(), 5000);
// @flow
'use strict';
const PassThrough = require('stream').PassThrough;
const spawn = require('child_process').spawn;
const _ = require('lodash');
type Options = {
channels?: number,
sampleRate?: number,
endianness?: 'LE',
byteRate?: 16
};
class Microphone extends PassThrough {
_proc: Object;
constructor (options?: Options) {
super();
options = _.defaults(options || {}, {
channels: 1,
sampleRate: 16000,
endianness: 'LE',
byteRate: 16
});
this._proc = spawn('arecord', [
'-q',
'-c', options.channels,
'-r', options.sampleRate,
'-f', `S${options.byteRate}_${options.endianness}`, // S=signed, 16bits, little-endian,
'-t', 'raw'
], {
stdio: [ 'ignore', 'pipe', 'ignore' ] // pipe stdout only
});
this._proc.stdout.pipe(this);
}
stop () {
this._proc.kill();
}
}
module.exports = Microphone;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment