Aligning triggers with audio replay

Hi, I am trying to send a serial port pulse at the onset of the replay of a sound file in a trial.

I set up a task in builder and modified it to improve the delay between the pulse and the onset of the audio to 1-5ms. 80% of trials have a delay of 1ms, but some come in at 5ms.

Here the relevant parts of the script (at least what I thought is relevant :)):

prefs.hardware['audioLatencyMode'] = '3'
...
for thisAudio_loop in audio_loop:
    ...
    audio_sample.play(when=win)  # sync with win flip
    win.callOnFlip(send_ttl, ttl_code)
    ...
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

Does anyone have any advice to further improve that timing, I would be okay with 1ms delays, the few trials that have 5ms would be great to improve on.

Best,
Max

If anyone has any pointers, I would apprechiate it, still trying to improve this.

The “when” argument schedules the playback based on the expected next screen flip, which should just be based on the framerate, while callOnFlip triggers when the flip actually occurs. What this is might be telling you is that there’s about 4ms of frame-lag of about 20% of the time.

To get the TTL aligned with the audio playback, instead of using “when”, you could try creating a function that plays the audio (immediately) and sends the TTL signal, and then use callOnFlip to call that function, i.e.,

def playAndTTL(audio_sample, ttl_code):
    audio_sample.play()
    send_ttl(ttl_code)
    ...

for thisAudio_loop in audio_loop:
    ...
    win.callOnFlip(playAndTTL, audio_sample, ttl_code)

That would put the audio playback and the TTL on the same timer (i.e., when the flip actually happens, not when it’s expected).