All files / noise-generator/lib node-audio-element.js

100% Statements 41/41
50% Branches 1/2
100% Functions 12/12
100% Lines 41/41
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      7x 7x 7x     7x 7x 7x 30x 24x 24x 24x 24x 24x 24x 24x 24x       7x 7x       14x 30x 30x 30x 30x 30x 30x           14x 14x   14x 14x     12x 12x     4x 4x           7x 7x 7x 7x 14x 14x 14x 14x       7x  
// TODO: this should be separated into a separate module
'use strict'
 
const uuid = require('uuid/v4')
const JSONStream = require('JSONStream')
const spawn = require('electron-spawn')
 
function initElectron (audios, pending) {
  const objects = JSONStream.parse()
  const electron = spawn(`${__dirname}/electron.js`)
  objects.on('data', (data) => {
    Object.keys(data).forEach(command => {
      const params = data[command]
      const { id, val, commandId } = params
      audios[id][command] = val
      Eif (pending[commandId]) {
        const { resolve, rejectTimeout } = pending[commandId]
        resolve(val)
        clearTimeout(rejectTimeout)
        delete pending[commandId]
      }
    })
  })
  electron.stdout.pipe(objects)
  return electron
}
 
function commandInstruction ({pending, id, electron}) {
  return function sendCommand (commandName, val) {
    return new Promise((resolve, reject) => {
      const commandId = uuid()
      const command = {[commandName]: {id, commandId, val}}
      const rejectTimeout = setTimeout(reject, 500) // TODO: config override
      pending[commandId] = {resolve, rejectTimeout}
      electron.stdin.write(JSON.stringify(command))
    })
  }
}
 
function api ({path, id, audios, electron, pending}) {
  const sendCommand = commandInstruction({pending, id, electron})
  return {
    play: () => {
      const commandName = 'play'
      return sendCommand(commandName)
    },
    loop: (val) => {
      const commandName = 'loop'
      return sendCommand(commandName, val)
    },
    volume: (val) => {
      const commandName = 'volume'
      return sendCommand(commandName, val)
    }
  }
}
 
function createAudio () {
  let audios = {}
  let pending = []
  const electron = initElectron(audios, pending)
  return function Audio (path) {
    const id = uuid()
    audios[id] = {}
    electron.stdin.write(JSON.stringify({open: {path, id}}))
    return api({path, id, audios, electron, pending})
  }
}
 
module.exports = createAudio