const http = require('http'), fs = require('fs'), { spawn } = require('child_process'); const { WebSocketServer } = require('ws'); const page = fs.readFileSync('index.html'); const srv = http.createServer((q, r) => { if (q.url.split('?')[0] !== '/mic') { r.statusCode = 404; return r.end(); } r.setHeader('content-type', 'text/html'); r.end(page); }); const wss = new WebSocketServer({ server: srv, path: '/mic/ws' }); let active = null; wss.on('connection', ws => { if (active) { try { active.ws.close(); } catch (e) {} try { active.p && active.p.stdin.end(); } catch (e) {} } const me = { ws, p: null }; active = me; ws.isAlive = true; ws.on('pong', () => { ws.isAlive = true; }); ws.on('message', (d, bin) => { if (!bin) { if (me.p) return; let rate = 48000; try { rate = parseInt(JSON.parse(d.toString()).rate) || 48000; } catch (e) {} me.p = spawn('paplay', ['--raw', '--rate=' + rate, '--format=s16le', '--channels=1', '--latency-msec=150']); me.p.on('error', e => console.log('paplay error', e.message)); me.p.stdin.on('error', () => {}); console.log('mic start', rate); return; } if (me.p) me.p.stdin.write(d); }); ws.on('close', () => { if (me.p) me.p.stdin.end(); if (active === me) active = null; console.log('mic stop'); }); }); setInterval(() => wss.clients.forEach(ws => { if (!ws.isAlive) return ws.terminate(); ws.isAlive = false; ws.ping(); }), 20000); srv.listen(8090);