Help writing a simple MIDI clock source

Support & discussion regarding DAWs and MIDI sequencers.

Moderators: MattKingUSA, khz

Post Reply
martibs
Established Member
Posts: 123
Joined: Mon Oct 15, 2018 7:06 pm
Location: Oslo, Norway
Has thanked: 34 times
Been thanked: 15 times

Help writing a simple MIDI clock source

Post by martibs »

I want to build a simple program to use as my MIDI clock source for synchronizing my hardware and software instruments. All I want it to do, is to take BPM as an input and send MIDI clock messages based on that number, as well as the possibility to send MIDI start and stop.

I tried to write it in Python, but it didn't turn out too good. The actual BPM output was 1 BPM lower than what was input, and the pulses was very unstable. Here is the code for reference:

Code: Select all

#!/bin/python3

from threading import Timer
import mido

# set backend
mido.set_backend('mido.backends.rtmidi/UNIX_JACK')

# define message
msgClock = mido.Message('clock')
#msgStart = mido.Message('start')
#msgStop = mido.Message('stop')

# define port
outport = mido.open_output('output', client_name='Simple Midi Clock')

# define BPM
BPMVALUE = 133.0

def setMidiPulseRate(BPMVALUE):
    MIDIPULSERATE = (60000000 / (24 * BPMVALUE)) / 1000000
    return MIDIPULSERATE

def sendMidiMessage(midiMsg):
    outport.send(midiMsg)

class MyInfiniteTimer():
    """
    This thread sends MIDI pulses indefinately
    """
    def __init__(self, rate, hfunction, message):
        self.rate = rate
        self.hfunction = hfunction
        self.thread = Timer(self.rate, self.handle_function)
        
    def handle_function(self):
        self.hfunction(message)
        self.thread = Timer(self.rate, self.handle_function)
        self.thread.start()
        
    def start(self, rate):
        self.rate = rate
        self.thread = Timer(self.rate, self.handle_function)
        self.thread.start()
        
    def cancel(self):
        self.thread.cancel()

# run
midiPulseRate = setMidiPulseRate(BPMVALUE)

t = MyInfiniteTimer(midiPulseRate, sendMidiMessage, msgClock)
t.start(midiPulseRate)
Is Python a poor choice of language for this type of application? Do I need to write it in C or Go? I'm not really a programmer, so I don't know what I'm doing here. If anyone can point me in the right direction, I'd be grateful.
User avatar
LAM
Established Member
Posts: 992
Joined: Thu Oct 08, 2020 3:16 pm
Has thanked: 140 times
Been thanked: 348 times

Re: Help writing a simple MIDI clock source

Post by LAM »

Hi @martibs,
I would suggest to have a look at:
https://github.com/x42/jack_midi_clock
or
https://github.com/x42/mclk.lv2
first.

I found this python program that should already do that:
https://github.com/ElliotGarbus/MidiClockGenerator

Hope it helps

in mix, nobody can hear your screen

Post Reply