From f922271cf2a09816bd07f258dd008648590ae15d Mon Sep 17 00:00:00 2001 From: Aron Homberg Date: Sat, 29 Mar 2014 16:59:48 +0100 Subject: [PATCH] Implemented "midimessage" event dispatching on noteOn/noteOff MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the visual keyboard of the synth gets clicked, a midi message event gets created and dispatched on window.onmidimessage (on window because there is no prototype to dispatch on currently). This allows third party software to use the virtual keyboard clicks as MIDI input. This impl. is using the data structure of the WebMIDIApi shim to be inter-operable and standard conform. Thank you @cwilso — WebMIDIApi is awesome! --- js/synth.js | 51 +++++++++++++++++++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 16 deletions(-) diff --git a/js/synth.js b/js/synth.js index abbfd2f..52fcf1e 100644 --- a/js/synth.js +++ b/js/synth.js @@ -68,30 +68,49 @@ var revNode = null; var revGain = null; var revBypassGain = null; +function createMidiMessageEvent(note, velocity) { + + var evt = document.createEvent( "Event" ); + evt.initEvent( "midimessage", false, false ); + evt.data = new Uint8Array(3); + evt.data[0] = 144; // channel 1 + evt.data[1] = note; + evt.data[2] = velocity || 0; + + if (window.onmidimessage && typeof window.onmidimessage == 'function') { + window.onmidimessage( evt ); + } +} + function frequencyFromNoteNumber( note ) { - return 440 * Math.pow(2,(note-69)/12); + return 440 * Math.pow(2,(note-69)/12); } function noteOn( note, velocity ) { - if (voices[note] == null) { - // Create a new synth node - voices[note] = new Voice(note, velocity); - var e = document.getElementById( "k" + note ); - if (e) - e.classList.add("pressed"); - } + + createMidiMessageEvent(note, velocity); + + if (voices[note] == null) { + // Create a new synth node + voices[note] = new Voice(note, velocity); + var e = document.getElementById( "k" + note ); + if (e) + e.classList.add("pressed"); + } } function noteOff( note ) { - if (voices[note] != null) { - // Shut off the note playing and clear it - voices[note].noteOff(); - voices[note] = null; - var e = document.getElementById( "k" + note ); - if (e) - e.classList.remove("pressed"); - } + createMidiMessageEvent(note); + + if (voices[note] != null) { + // Shut off the note playing and clear it + voices[note].noteOff(); + voices[note] = null; + var e = document.getElementById( "k" + note ); + if (e) + e.classList.remove("pressed"); + } } function $(id) {