node.jseventsmax-msp-jitterableton-live

How to catch custom events in NodeJS


Okay so this is probably a stupid question, I've tried searching here and on Google but nothing seems to really answer it because it's just not specific enough for my current situation (there's like tons of info about JS events I know, also I've been told no question is really stupid).

I want to emit a custom event in NodeJS whenever a certain frequency has been reached. So when I'm playing a song, it hits over 80 dB, I want to emit a event.

How do I catch this event in my web browser? I probably need to fire a server, that I know. But how do I send the events from my server, and more importantly, how do I catch them client-side?

(So that I can use A-frame and make some nice audiovisualisation).

This is my current code, currently I'm doing nothing with my server, but my audio analysing (from Ableton) works.

'use strict';

let Max4Node = require('max4node');
let EventEmitter = require("events").EventEmitter;
let ee = new EventEmitter();

// Server
let http = require('http');
let handleRequest = (request, response) => {
    response.end(`It works! ${request.url}`);
}
let server = http.createServer(handleRequest);
const PORT=8080; 
server.listen(PORT, function(){
    console.log(`Server listening on: http://localhost:${PORT}`);
});

let max = new Max4Node();
max.bind();

// Event listeners
ee.on('kick', (data) => {
    console.log(`kick ${data}`);
});

ee.on('clap', (data) => {
    console.log(`clap ${data}`);
});

ee.on('hat', (data) => {
    console.log(`hat ${data}`);
});

// Observe the low-pass filtered track
max.observe({
  path: 'live_set tracks 0',
  property: 'output_meter_level'
})
.on('value', function(val) {
  val > 0.8 ? ee.emit('kick', val) : null;
});

// Observe the high-pass filtered track
max.observe({
  path: 'live_set tracks 3',
  property: 'output_meter_level'
})
.on('value', (val) => {
  val > 0.8 && val < 0.9 ? ee.emit('clap', val) : null;
  val > 0.9 ? ee.emit('hat', val) : null;
});

I hope someone can give me a better insight on how to tackle this situation, feedback/tips are welcome!


Solution

  • You need some form of getting that event from the server to the web client in somewhat realtime - the first solution everyone thinks of is WebSockets (which works really well, especially if you abstract it away with a library like Socket.IO). This allows you to communicate both from the server to the client and from the client to the server in realtime.

    Another option is to use Server Side Events, which is done over regular HTTP and is super simple to do in JavaScript. This allows the server to send events to the client in realtime, but is unidirectional. If all you need is to send the events to the browser, it's worth taking a look. (Emojitracker is built using this tech, and the creator talks about this a bit more here)