All files microphone.js

67.42% Statements 60/89
52.78% Branches 19/36
72.73% Functions 8/11
67.42% Lines 60/89
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219      1x 1x     1x     1x   1x 1x     1x 1x           9x   9x   9x                   9x   9x   20x     2x           9x 9x 9x 9x   9x 1x     8x   8x   1x       7x         7x 4x 4x     4x           2x               4x   4x   4x         8x 5x       8x 8x 8x 8x 8x 18x 18x 8x   18x   18x       8x           8x     8x             8x 2x 2x 2x     8x 1x                         8x     8x                                                                                       1x 1x                     1x   1x  
'use strict';
 
// Dependencies: Built-in
const cp = require('child_process');
const Emitter = require('events').EventEmitter;
 
// Dependencies: Internal
const CaptureStream = require('./capture-stream');
 
// Program specific
const priv = new WeakMap();
 
try {
  cp.spawnSync('kill -9 $(pgrep "aplay")');
} catch (error) {}
 
try {
  cp.spawnSync('kill -9 $(pgrep "arecord")');
} catch (error) {}
 
 
class Microphone extends Emitter {
  constructor(options) {
    super();
 
    options = options || {};
 
    const state = {
      arecord: null,
      aplay: null,
      currentTime: 0,
      isListening: false,
      interval: null,
      cs: new CaptureStream(),
      time: null,
    };
 
    priv.set(this, state);
 
    Object.defineProperties(this, {
      currentTime: {
        get: () => Number(state.currentTime.toFixed(3)),
      },
      isListening: {
        get: () => state.isListening,
      },
    });
  }
 
  listen(options) {
    const state = priv.get(this);
    const time = 0;
    let offset = null;
    let args = [];
 
    if (state.isListening) {
      return state.cs;
    }
 
    options = options || {};
 
    if (Array.isArray(options)) {
      // mic.listen(['-f', 'cd', '-c', 1, '-r', 48000 ]);
      args = options;
    } else {
      // Don't need to check for null, since those are handled above
      /* istanbul ignore else */
      if (typeof options === 'object') {
        //  mic.listen({
        //    ...
        //  });
        //
        args = Object.keys(options).reduce((accum, key) => {
          const value = options[key];
          let option = '';
 
          /* istanbul ignore else */
          if (key.length === 1) {
            //  mic.listen({
            //    c: 1,
            //    f: 'cd',
            //  });
            //
            option = '-';
          }
 
          //  mic.listen({
          //    '-c': 1,
          //    '-f': 'cd',
          //  });
          //
          option += key;
 
          accum.push(option, value);
 
          return accum;
        }, []);
      }
    }
 
    if (args.length === 0) {
      args = defaults.slice();
    }
 
    /* istanbul ignore else */
    if (state.arecord === null) {
      state.isListening = true;
      state.currentTime = 0;
      state.startTime = Date.now();
      state.interval = setInterval(() => {
        const now = Date.now();
        if (offset === null) {
          offset = now - state.startTime;
        }
        state.currentTime = time + (now - state.startTime - offset) / 1000;
 
        this.emit('timeupdate', this.currentTime);
      }, 100);
 
      // Apply some reasonable defaults...
      arecord.keys.forEach(key => {
        if (!args.includes(key)) {
          args.push(key, arecord.options[key]);
        }
      });
 
      state.arecord = cp.spawn('arecord', args);
 
      /* istanbul ignore if */
      if (this.debug) {
        state.arecord.stderr.on('data', data => {
          const lines = data.toString().split('\n').filter(Boolean).map(line => line.trim());
          console.error(lines.join('\n'));
        });
      }
 
      state.arecord.stdout.on('data', data => {
        state.cs.push(data);
        this.emit('data', data);
        this.emit('timeupdate', this.currentTime);
      });
 
      state.arecord.on('close', (code, signal) => {
        Iif (code !== null && signal === null) {
          if (state.interval) {
            clearInterval(state.interval);
          }
          state.arecord = null;
          state.currentTime = 0;
          state.startTime = 0;
          state.isListening = false;
 
          this.emit('close');
        }
      });
 
      this.emit('listen');
    }
 
    return state.cs;
  }
 
  monitor(catpureStream) {
    const state = priv.get(this);
 
    if (state.isListening) {
      state.aplay = cp.spawn('aplay', ['-f', 'cd' /*, '-D', 'plughw:0,0' */ ]);
    }
 
    if (catpureStream) {
      return catpureStream.pipe(state.aplay.stdin);
    } else {
      return state.cs.pipe(state.aplay.stdin);
    }
  }
 
  stop() {
    const state = priv.get(this);
 
    if (!state.isListening) {
      return this;
    }
 
    state.isListening = false;
 
    if (state.interval) {
      clearInterval(state.interval);
    }
 
    if (state.arecord) {
      state.arecord.kill('SIGTERM');
      state.arecord = null;
    }
 
    if (state.aplay) {
      state.aplay.kill('SIGTERM');
      state.aplay = null;
    }
    this.emit('stop');
    return this;
  }
}
 
const defaults = ['-f', 'cd', '-r', '48000' /*, '-D', 'plughw:0,0' */ ];
const arecord = {
  options: {
    // Disable until we can figure out how best to
    // apply these without clumisly over-riding related flags
    // '-f': 'cd',
    // '-c': 1,
    // '-r': 48000,
    // '-D': 'plughw:0,0',
  },
};
 
arecord.keys = Object.keys(arecord.options);
 
module.exports = Microphone;