web audio api – How to measure latency between midi instrument and web midi api?

When using the web midi api for receiving midi messages from a midi instrument (via usb), how can we measure the latency time, that is: the time it took from playing a note with the instrument to receiving the corresponding midi message?

Ideally we’d like to start a clock in web (audioContext clock or high res clock in main thread like performance.now or document.timeline) and be able to tell at which point in time (on that clock) the note has been played on the midi instrument – because the time we receive the corresponding midi message is o/c later in time than the actual play time (buffer processing, time the signal took from one output to another..)

Can midi clock messages sent by the midi instrument somehow be used for measuring latency? If so, how?


Ideas we already tried out:

  1. let user hit some keyboard key and a midi drum note as simultaneously as possible multiple times, then take average difference between the time of keypress and the time of the midi message for that drum note
  2. let user hit drum note when a moving black line reaches a non-moving red line and then do the same as above
  3. schedule metronome beeps and let user hit drum notes as simultaneously as possible to those beeps and again measure differences as above

possible downsides:

  1. depends on user’s ability to do those 2 things simultaneously
  2. the line movement is done via requestAnimationFrame, so the line gets re-drawn every x fps (in my case around every 20ms) – but this inaccuracy would probably even out with a high number of repetitions(?)
  3. the accuracy of this approach depends on another sort of latency: the scheduled beep time (via web audio api) and the time the user hears the beep (outputLatency + time of sound waves to user’s ear)

Thank you!

Read more here: Source link