Skip to content

Instantly share code, notes, and snippets.

@niusounds
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save niusounds/ea054295a3459f849224 to your computer and use it in GitHub Desktop.

Select an option

Save niusounds/ea054295a3459f849224 to your computer and use it in GitHub Desktop.
WebAudio input to MIDI note number. AngularJS & jQuery is required.
angular.module('myApp').factory('audioContext', function() {
return new AudioContext();
});
angular.module('myApp').factory('midiNoteDetector', function(audioContext, $interval) {
var analyser = audioContext.createAnalyser();
var data = new Float32Array(analyser.fftSize / 2);
var promise;
var maxValue = -9999;
var maxIndex = -1;
var freq, note;
var prevFreq, prevNote;
return {
from: function(source) {
source.connect(analyser);
$interval.cancel(promise);
promise = $interval(loop.bind(this), 100);
},
on: function(eventName, handler) {
$(this).on(eventName, handler);
return this;
},
off: function(eventName, handler) {
$(this).off(eventName, handler);
return this;
}
};
function loop() {
analyser.getFloatFrequencyData(data);
maxValue = -9999;
angular.forEach(data, setMax);
freq = audioContext.sampleRate * maxIndex / analyser.fftSize;
note = Math.floor(12 * (Math.log(freq / 440) / Math.log(2)) + 69);
// notify changes
if (freq !== prevFreq) {
$(this).trigger('frequencyChange', [freq]);
}
if (note !== prevNote) {
$(this).trigger('noteChange', [note]);
}
prevFreq = freq;
prevNote = note;
}
function setMax(sample, idx) {
if (maxValue < sample) {
maxValue = sample;
maxIndex = idx;
}
}
});
angular.module('myApp').controller('controller', function(audioContext, midiNoteDetector) {
var source = audioContext.createOscillator();
source.start();
midiNoteDetector.from(source);
source.connect(audioContext.destination);
midiNoteDetector.on('frequencyChange', function(e, freq) {
console.log(freq);
}).on('noteChange', function(e, note) {
console.log(note);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment