Skip to content

Instantly share code, notes, and snippets.

@mallendeo
Last active March 30, 2023 12:31
Show Gist options
  • Save mallendeo/0fb8679ae3d743932cdba4d6111e2883 to your computer and use it in GitHub Desktop.
Save mallendeo/0fb8679ae3d743932cdba4d6111e2883 to your computer and use it in GitHub Desktop.
Get mic audio stream in real time and send it vía websockets to a server

Dependencies

sox, node

On Ubuntu/Debian:

sudo apt install sox nodejs

On macOS:

brew install sox nodejs

Install and run

npm i

node server.mjs

The client can be another linux or macOS machine.

** WARNING! lower down your volume before running the example since it will produce echo **

node client.mjs

If you want to stream the audio to another device (e.g a raspberry pi intercom system) you can filter by meta.id on client.on('stream', (stream, meta) => ...)

import { BinaryClient } from 'binaryjs';
import { spawn } from 'child_process';
const SERVER_IP = '127.0.0.1';
const PORT = 9000;
const client = BinaryClient(`ws://${SERVER_IP}:${PORT}`);
const args = ['-d', '-q', '-b', '16', '-r', '44100', '-c', '2', '-t', 'wav','-'];
const speaker = spawn('play', ['-']);
const sox = spawn('sox', args);
client.on('open', () => {
const stream = client.createStream();
sox.stdout.on('data', chunk => {
if (stream.writable) {
stream.write(chunk)
}
});
client.on('stream', (stream, meta) => {
stream.on('data', data => speaker.stdin.write(data))
});
});
process.on('SIGTERM', () => {
sox.stdin.pause();
sox.kill();
client.close();
});
{
"dependencies": {
"binaryjs": "^0.2.1"
},
"author": "@mallendeo",
"license": "MIT"
}
import { BinaryServer } from 'binaryjs';
const server = BinaryServer({ port: 9000 });
server.on('connection', client => {
console.log('Client connected: ', client.id);
client.on('stream', stream => {
stream.on('data', data => {
client.send(data, { id: client.id });
});
});
});
process.on('SIGTERM', () => {
speaker.stdin.pause();
speaker.kill();
});
@epic80
Copy link

epic80 commented Jan 11, 2019

Hi,

I am interested in your project, is it still functional? If so, possible to have the entire project?

Thank you

@vuk2295
Copy link

vuk2295 commented Aug 25, 2021

Can you make some Readme file? Most people didn't know how to run this example.

@mallendeo
Copy link
Author

mallendeo commented Aug 31, 2021

@vuk2295 I just updated the example. It's from an old raspberry pi project, and it's very inefficient since it uses uncompressed raw audio.

@epic80 I never saw this comment until github notified me about @vuk2295 one, sorry about that 😓. This still works with the latest version of node. I don't remember if I ever made a repo for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment