Python metronome with twisted: How to pass parameter for iteration?

488 Views Asked by At

I wanted to build a metronome in Python.

I have 2 sound files. Every second the first sound file should played and every fourth second the second sound file should played.

I found the twisted module, but couldn't figure out how to pass an parameter and iterate it. So I have the variable counter which I want to iterate, but it's not working with following code:

import simpleaudio as sa
from twisted.internet import task
from twisted.internet import reactor


def beat(bpm, counter):
    timeout = 60/bpm
    l = task.LoopingCall(play_beat, counter=counter)
    l.start(timeout)
    reactor.run()


def play_beat(counter):
    counter += 1
    print(counter) #This prints always 2, I am expecting an iteration like 2, 3, 4, 5, 6 ...
    if counter % 4 == 0:
        wave_obj = sa.WaveObject.from_wave_file("wav/beat_end.wav")
    else:
        wave_obj = sa.WaveObject.from_wave_file("wav/beat_start.wav")
    play_obj = wave_obj.play()
    play_obj.wait_done()
    pass

beat(60, 1)
1

There are 1 best solutions below

0
On

Here's another solution.

import simpleaudio as sa
from twisted.internet import task
from twisted.internet import reactor

def beat(bpm, wave_obj):
    timeout = 60.0 / bpm
    l = task.LoopingCall(play_beat, wave_obj)
    l.start(timeout)

def play_beat(wave_obj):
    wave_obj.play()

beat_start = sa.WaveObject.from_wave_file(...)
beat_end = sa.WaveObject.from_wave_file(...)

bpm = 60.0
bps = bpm / 60
reactor.callLater(0 / bps, beat, bpm / 4, beat_start)
reactor.callLater(1 / bps, beat, bpm / 4, beat_start)
reactor.callLater(2 / bps, beat, bpm / 4, beat_start)
reactor.callLater(3 / bps, beat, bpm / 4, beat_end)
reactor.run()

It may be noteworthy that I've removed the wait_done call. If you block the reactor thread like that, you can expect less reliable scheduling of time-based events.