All files / noise-generator index.js

100% Statements 20/20
100% Branches 2/2
100% Functions 5/5
100% Lines 20/20
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    7x 7x     14x     7x   7x 7x 7x 7x   14x 14x 14x 12x 10x   4x       5x 4x 2x       2x   4x     1x          
'use strict'
 
const fs = require('fs')
const createAudio = require('./lib/node-audio-element.js')
 
function isAudioFile (filename) {
  return /\.mp3$/.test(filename)
}
 
module.exports = {
  async noiseGenerator (dir) {
    const Audio = createAudio()
    const files = fs.readdirSync(dir)
    const audioFileNames = files.filter(isAudioFile)
    const audioFiles = await Promise.all(
      audioFileNames.map(async filename => {
        const aud = new Audio(`${dir}/${filename}`)
        try {
          await aud.play()
          await aud.loop(true)
          return aud
        } catch (e) {
          throw new Error('timed out waiting for electron process')
        }
      })
    )
    return (...volumes) => {
      if (volumes.length !== audioFiles.length) {
        throw new Error(
          `invalid argument length, received ${volumes.length} but have ${audioFiles.length} files loaded`
        )
      }
      return Promise.all(
        volumes.map((value, i) => {
          return audioFiles[i].volume(value)
        })
      ).catch((e) => {
        throw new Error('timed out waiting for electron process')
      })
    }
  }
}