From 15de6776a959c0b267b6f601417caf1f973b3b38 Mon Sep 17 00:00:00 2001 From: Florrie Date: Fri, 22 Mar 2019 17:51:06 -0300 Subject: Initial commit --- index.js | 113 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 index.js (limited to 'index.js') diff --git a/index.js b/index.js new file mode 100644 index 0000000..72beebf --- /dev/null +++ b/index.js @@ -0,0 +1,113 @@ +const { spawn } = require('child_process'); +const FIFO = require('fifo-js'); +const http = require('http'); + +class TrackPlayer { + constructor(file) { + this.file = file; + this.volume = 0; + this.storedVolume = this.volume; + } + + loadProcess() { + this.fifo = new FIFO(); + this.process = spawn('mpv', [ + '--no-video', + '--loop', + '--volume=' + this.volume, + '--input-file=' + this.fifo.path, + this.file, + ]); + + this.process.stderr.pipe(process.stderr); + } + + sendCommand(command) { + if (this.fifo) { + this.fifo.write(command); + } + } + + seekToStart() { + this.sendCommand('seek 0 absolute'); + } + + pause() { + this.sendCommand('set pause yes'); + } + + play() { + this.sendCommand('set pause no'); + } + + setVolume(volume) { + if (Math.floor(volume) !== this.storedVolume) { + this.storedVolume = Math.floor(volume); + this.sendCommand(`set volume ${volume}`); + } + this.volume = volume; + } +} + +const tracks = { + mantis: new TrackPlayer('track1.wav'), + bass: new TrackPlayer('track2.wav'), + main: new TrackPlayer('track3.wav') +}; + +for (const track of Object.values(tracks)) { + track.loadProcess(); + track.pause(); +} + +setTimeout(() => { + for (const track of Object.values(tracks)) { + track.seekToStart(); + track.play(); + } + + let targetMode = [ + {track: 'main', volume: 100} + ]; + + setInterval(() => { + if (!Array.isArray(targetMode)) { + console.log('targetMode is not an array.'); + targetMode = []; + } + + for (const [key, track] of Object.entries(tracks)) { + const mode = targetMode.find(m => m.track === key) || {volume: 0}; + track.setVolume(track.volume + 0.1 * (mode.volume - track.volume)); + } + }, 100); + + const server = http.createServer((request, response) => { + response.setHeader('Access-Control-Allow-Origin', '*'); + response.setHeader('Access-Control-Allow-Headers', 'Authorization, Cache-Control, Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'); + console.log('Got request.'); + + if (request.method === 'GET') { + response.write('Please use POST.'); + response.end(); + } else if (request.method === 'POST') { + let allData = ''; + request.on('data', data => { + allData += data; + }); + request.on('end', () => { + try { + targetMode = JSON.parse(allData); + response.write('Set.'); + } catch (error) { + response.write('Invalid JSON.'); + } + response.end(); + }); + } else { + response.end(); + } + }); + + server.listen(8000); +}, 250); -- cgit 1.3.0-6-gf8a5