Capture system audio output with Nodejs

Raza Gill picture Raza Gill · Jul 30, 2014 · Viewed 10.1k times · Source

Is there a way in javascript or is there a nodejs module, that I can use to capture the output of a system (win/osx). For example, if a user is playing something via iTunes/MPlayer (any music player), I can capture the audio stream that's going to the speakers (output) and send it over the web?

Answer

PRS picture PRS · Apr 23, 2018

I'm about to start some dev work on a similar project but was having issues getting node-core-audio to install so I had to find a different module. https://www.npmjs.com/package/naudiodon looks to be a good replacement and it installs just fine. Will update with my findings after I've had some time to play around with it.

Update:

For my project, I wanted to run spectrum analysis on the system audio out. I ended up using Soundflower and SoundflowerBed to setup audio routing. Once I had that working, I was able to use naudiodon to record the raw audio data.

This was tested in Node 8.17.0, with my fork of naudiodon which removed console logging on buffer overflow because it messed with my terminal UI. My fork is available here if you want, but I don't think I did anything specific for this to work.

github:psnyder/naudiodon#feature/dont-write-to-console-on-buffer-overflow

I recommend you run this line by line in the node console after installing the required packages.

const fs = require('fs');
const portAudio = require('naudiodon');

// Use this to find out the device id for soundflower
console.log(portAudio.getDevices());

// create audio io instance
const ai = new portAudio.AudioIO({
  inOptions: {
    channelCount: 2,
    sampleFormat: portAudio.SampleFormat16Bit,
    sampleRate: 44100,
    deviceId: 2, // choose id for Soundflower (2CH)
    closeOnError: true,
  }
});
const ws = fs.createWriteStream('rawAudio.raw');
ai.pipe(ws);
ai.start();
// Wait a while as you record the audio in -- check your sound levels in SoundflowerBed, etc.
// When you are done...
ai.quit();

Now in Audacity, you can File -> Import -> Raw Data and check for an audio waveform.