On Github mollerse / diysynth
Stian Veum Møllersen / @mollerse
BEKK
For as long as i can remember i've loved making sounds. Now, I never became a musician by trade, I chose to become a developer instead. But i never lost that love for music and creativity. With the introduction of the WebAudioAPI to the most ubiquitous runtime available, its a good a time as ever to get rolling making some sounds.
Sound is the perception of waves that travel through some medium, usually air. Waves are generated by oscillating between compression and expansion. Think of a piano, where a hammer strikes a wire to make it oscillate. Or a guitar where the player strums the strings to create vibrations.
We can use an oscillator to generate a wave. An oscillator generates an electrical signal that will oscillate in the same manner as a physical thing. These formed the basis of the first electronic music synthersizers.
Oscillators were physical things in the beginning. They needed voltage to pass through them to generate the soundwave. However, we now have the ability to create oscillators in the browser using JavaScript!
var context = new AudioContext(); var oscillator = context.createOscillator(); oscillator.start();
var amp = context.createGain();
oscillator.connect(amp); amp.connect(context.destination);
The WebAudio entities are structured as a graph. With nodes of different kinds that can be connected to form intricate sound processing units.
function Note() { //Initialization and node-creation here function start() { amp.gain.value = 1; } function stop() { amp.gain.value = 0; } return {start, stop}; }
A standard that defines a protocol, digital interface and connectors for musical instruments.
navigator.requestMIDIAccess() .then(midiConnected);
function midiConnected(midi) { for(entry of midi.inputs.values()) { entry.onmidimessage = function(msg) { var [code, note, velocity] = msg.data; code === 144 ? on(note) : off(note); }; } }
function frequencyFromNoteNumber(note) { return 440 * Math.pow(2,(note-69)/12); } oscillator.frequency.value = frequencyFromNoteNumber(note);
oscillator.type = 'sawtooth';
var notes = {}; function on(note) { var n = Note(note); notes[note] = n; n.start(); } function off(note) { notes[note].stop(); delete notes[note]; }
Multiple detuned sawtooth oscillators. Heavily used in the EDM style of music.
Originally from the Roland JP-8000. It was made to emulate more than one sawtooth oscillator. Each sawtooth oscillator is slightly detuned against one another. This sort of sound gained some notoriety in the early 2000s with the rise of electronic dance music.
//Inside Note-function for (var i = 0; i < numSaws; i++) { makeSaw(i, numSaws); }
function makeSaw(i, numSaws) { //Oscillator creation and init saw.detune.value = -detune + i * 2*(detune/(numSaws-1)); }
You are now a musician.
Stian Veum Møllersen / @mollerse
BEKK