Midi and audio latency in p5.sound

Hi, I’ve been playing around with the Web MIDI API for Chrome and wanted to see if I could make a web based synth. So I’ve just downloaded the p5 libraries and much to my surprise, it only took me a few minutes to set up a basic polysynth. That’s amazing!
The problem however is the latency between keypress and sound. It’s ok for testing, but it’s too slow to actually play music. Is there any way to optimize this? Apologies if this is around somewhere in the reference. I couldn’t find it.

This is my code:

MidiConnect();
function MidiConnect() { 
	try{navigator.requestMIDIAccess({ sysex: false }).then(onMIDISuccess, onMIDIFailure); }
	catch(e) {}
}

function onMIDIFailure(msg) { console.log("MIDI access failure."); }
function onMIDISuccess(midiAccess) { 
	console.log("MIDI access success."); 	
	parseMIDIInput(midiAccess); 	
	midi = midiAccess;
}

function parseMIDIInput(midiAccess) {
	midiAccess.inputs.forEach(function (entry) 	{ 	
		entry.onmidimessage = onMIDIMessage.bind(entry); 
	});
}


function onMIDIMessage(event, entry){		
	entry = this;
	var c = event.data[0];
	var n = event.data[1];
	var v = event.data[2];
	if(c == 144) PlayNote(n,v);
	
}

var polysynth = new p5.PolySynth();

function PlayNote(n,v){	
	var f = NtoHz(n);	
	polysynth.play(f,0.1,0,0.1);	
}

function NtoHz(n){return 440*Math.pow(2,(n-69)/12)}

(for some reason midiToFreq didn’t work, so I copied the code to NtoHz)

1 Like