Skip to content

Instantly share code, notes, and snippets.

@bobvanluijt
Created June 7, 2020 18:52
Show Gist options
  • Save bobvanluijt/d11301ebaedb016a5ddce42a3ecb3556 to your computer and use it in GitHub Desktop.
Save bobvanluijt/d11301ebaedb016a5ddce42a3ecb3556 to your computer and use it in GitHub Desktop.
Microtonal JS
// https://pages.mtu.edu/~suits/notefreqs.html
// https://pages.mtu.edu/~suits/NoteFreqCalcs.html
// create web audio api context
var audioCtx = new(window.AudioContext || window.webkitAudioContext)();
// microtonal division
var microtonalDiv = 24;
var c4 = 261.6256;
function oscillateNote(frequency, duration) {
// create Oscillator node
var oscillator = audioCtx.createOscillator();
oscillator.type = 'wave';
oscillator.frequency.value = frequency; // value in hertz
oscillator.connect(audioCtx.destination);
oscillator.start();
setTimeout(
function() {
oscillator.stop();
}, duration);
}
function noteToFreq(note, pitch, octave){
// note = note.toLowerCase().charCodeAt(0) - 97;
octave -= 4;
// determine tone
freq = note.toLowerCase()
// determine note
switch(note) {
case 'c':
freq = 0 + (octave * microtonalDiv);
break;
case 'd':
freq = 4 + (octave * microtonalDiv);
break;
case 'e':
freq = 8 + (octave * microtonalDiv);
break;
case 'f':
freq = 10 + (octave * microtonalDiv);
break;
case 'g':
freq = 14 + (octave * microtonalDiv);
break;
case 'a':
freq = 18 + (octave * microtonalDiv);
break;
case 'b':
freq = 22 + (octave * microtonalDiv);
break;
default:
console.error('NO TONE', freq)
return;
}
// determine microtonal note
// based on: https://github.com/0xfe/vexflow/wiki/Microtonal-Support
switch(pitch) {
case 'bb':
freq -= 4;
break;
case 'db':
freq -= 3;
break;
case 'b':
freq -= 2;
break;
case 'bs':
freq -= 1;
break;
case 'n':
break;
case '+':
freq += 1;
break;
case '#':
freq += 2;
break;
case '++':
freq += 3;
break;
case '##':
freq += 4;
break;
default:
console.error('NO PITCH', freq)
return;
}
return c4 * Math.pow(Math.pow(2, 1/microtonalDiv), freq);
}
function playNote(note, mnemonic, octave, duration){
oscillateNote(noteToFreq(note, mnemonic, octave), duration);
console.log('playing: ' + noteToFreq(note, mnemonic, octave) + ' as ' + note + mnemonic + octave);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment