Skip to content

Instantly share code, notes, and snippets.

@kylemcdonald
Last active April 15, 2017 10:43
Show Gist options
  • Save kylemcdonald/6e4eda914f0210ac7ed48fbcd44524f3 to your computer and use it in GitHub Desktop.
Save kylemcdonald/6e4eda914f0210ac7ed48fbcd44524f3 to your computer and use it in GitHub Desktop.
ofxAubio beat detector sent over OSC.
// Example settings.xml:
//
// {
// "destination": "localhost",
// "port": 9090,
// "device": 2
// }
#include "ofMain.h"
#include "ofEventUtils.h"
#include "ofxOsc.h"
#include "ofxAubio.h"
#include "ofxGui.h"
#include "ofJson.h"
class ofApp : public ofBaseApp {
public:
ofxAubioBeat beat;
ofxAubioMelBands bands;
float lastBeat;
float fadeOut = .25;
float maxEnergy = 0;
vector<ofSoundDevice> devices;
ofxOscSender oscOut;
void setup(){
ofSetFrameRate(60);
ofSetBackgroundAuto(false);
ofJson settings = ofLoadJson("settings.json");
beat.setup();
ofAddListener(beat.gotBeat, this, &ofApp::beatEvent);
bands.setup();
devices = ofSoundStreamListDevices();
ofSoundStreamSettings soundSettings;
soundSettings.setInDevice(devices[settings["device"]]);
soundSettings.numInputChannels = 2;
soundSettings.numOutputChannels = 0;
soundSettings.setInListener(ofGetAppPtr());
ofSoundStreamSetup(soundSettings);
oscOut.setup(settings["destination"], settings["port"]);
}
void exit(){
ofSoundStreamStop();
ofSoundStreamClose();
}
void audioIn(float * input, int bufferSize, int nChannels){
beat.audioIn(input, bufferSize, nChannels);
bands.audioIn(input, bufferSize, nChannels);
}
void update(){
}
void draw(){
// update beat info
float beatTime = ofGetElapsedTimef() - lastBeat;
float alpha = ofMap(beatTime, 0, fadeOut, 255, 0, true);
ofClear(alpha);
// draw bands
ofSetColor(255);
ofSetLineWidth(3.);
ofPolyline bandPlot;
float curMaxEnergy = 0;
for (int i = 0; i < bands.nBands; i++) {
float energy = bands.energies[i];
curMaxEnergy = MAX(energy, curMaxEnergy);
float x = ofMap(i, 0, bands.nBands - 1, 0, 1);
float y = ofMap(bands.energies[i], 0, maxEnergy, 1, 0, true);
bandPlot.addVertex(ofVec3f(x, y, 0));
}
maxEnergy = MAX(curMaxEnergy, maxEnergy);
ofDrawBitmapString("Max Energy: " + ofToString(int(100 * maxEnergy)), 10, 20);
ofDrawBitmapString(ofToString(beat.bpm) + " bpm", 10, 40);
ofScale(ofGetWidth(), ofGetHeight());
bandPlot.draw();
}
void beatEvent(float & time) {
lastBeat = ofGetElapsedTimef();
ofxOscMessage msg;
msg.setAddress("/beat");
oscOut.sendMessage(msg);
}
};
int main() {
ofSetupOpenGL(640, 240, OF_WINDOW);
ofRunApp(new ofApp());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment