ambv / aiotone

A demo of using AsyncIO for music sequencing
MIT License
118 stars 9 forks source link

Less jitter with spin_sleep() #7

Open ghost opened 3 years ago

ghost commented 3 years ago

For anyone who is interested. I built sequencer based on aiotone that is sync-master and drives my DAW. I had quite some jitter compared to other midi-sequencers. Using spin_sleep() in the main loop, there is much less jitter. Of course there is a tradeoff: higher CPU load.

sleep_resolution is platform dependent. On linux 0.001s should be a good value. I am not aware of a good way to detect sleep_resolution.

import asyncio
from time import time

sleep_resolution = 0.001

async def spin_sleep(sleep_time):
    deadline = sleep_time + time()
    await asyncio.sleep(sleep_time - sleep_resolution)
    while deadline > time():
        await asyncio.sleep(0)

Currently my code isn't in a state for sharing, but I will put it on github soonish.

ghost commented 3 years ago

Here it is: https://github.com/bltbitblt/mus

I guess the most interesting part is: https://github.com/bltbitblt/mus/commit/a38e3d26a36f6964954f9617b1c807a875293d00

pulses is now a float and it waits til the second last pulse and sleeps the rest using spin_sleep().