# Midi and audio latency in p5.sound

**URL:** <https://discourse.processing.org/t/midi-and-audio-latency-in-p5-sound/1010>\
**Category:** Beginners\
**Created:** [June 16, 2018, 10:10am UTC](https://discourse.processing.org/t/midi-and-audio-latency-in-p5-sound/1010 "2018-06-16T10:10:50Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jjd](https://avatars.discourse-cdn.com/v4/letter/j/c4cdca/32.png) [@jjd](https://discourse.processing.org/u/jjd)\
**Post date:** [June 16, 2018, 10:10am UTC](https://discourse.processing.org/t/midi-and-audio-latency-in-p5-sound/1010/1 "2018-06-16T10:10:50Z")

</div>

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:

```auto
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)
