Controlling a toggle of a `while bool` loop with asyncIO

48 Views Asked by At

I am trying to create a sequencer using the mido library. For the sequencer, I want to be able to toggle it on and off using a button. How can I achieve this, using asyncIO for the sequencer?

I tried writing a function within the Sequencer class that toggles its state, then calling it from my main function:

sequencer.py:

async def runSequencer(self) -> None:
    while self.isRunning:
        #Sequencer code here

async def toggleSequencer(self) -> None:
    print(self.voice, "TOGGLE")
    if self.isRunning:
        await self.pauseSequencer()
    else:
        await self.runSequencer()
    await asyncio.sleep(0.001)

__main__.py:

async def readInport() -> None:
    for msg in inport.iter_pending():
        if (msg.type != 'sysex'):
            type, ch, note, vel = functions.unpack_message(msg)
            print(type, ch, note, vel) # print() mentioned below
            queue = []
            if type == "control_change" and note == 19 and vel == 127: # Wanted button pressed
                time.sleep(0.001)
                queue = [seq.toggleSequencer() for seq in sequencers]
        else:
            print("other")

        await asyncio.gather(*queue)

async def main():
    while True:
        await asyncio.gather(readInport())

if __name__ == "__main__":
    asyncio.run(main())

This runs the sequencers as intended when I first press the button, but the marked print() doesn't run when I press it again.

However, the notes stop playing for a microsecond when I press the button. This doesn't happen when I press any other button. (Edit: after checking now, it does seem to happen whenever I press any button.)


This is my first time working with asyncIO, and one of my first projects in python, so excuse my ignorance and the sloppiness that may be present in my code.

0

There are 0 best solutions below