|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Very basic MIDI synthesizer. |
| 3 | +
|
| 4 | +This only works in Python 3.x because it uses memoryview.cast() and a |
| 5 | +few other sweet Python-3-only features. |
| 6 | +
|
| 7 | +This is inspired by the JACK example program "jack_midisine": |
| 8 | +http://github.com/jackaudio/jack2/blob/master/example-clients/midisine.c |
| 9 | +
|
| 10 | +But it is actually better: |
| 11 | +
|
| 12 | ++ ASR envelope |
| 13 | ++ unlimited polyphony (well, "only" limited by CPU and memory) |
| 14 | ++ arbitrary many MIDI events per block |
| 15 | ++ can handle NoteOn and NoteOff event of the same pitch in one block |
| 16 | +
|
| 17 | +It is also worse: |
| 18 | +
|
| 19 | +- horribly inefficient (dynamic allocations, sample-wise processing) |
| 20 | +- unpredictable because of garbage collection (?) |
| 21 | +
|
| 22 | +It sounds a little better than the original, but still quite boring. |
| 23 | +
|
| 24 | +""" |
| 25 | +import jack |
| 26 | +import math |
| 27 | +import operator |
| 28 | +import threading |
| 29 | + |
| 30 | +# First 4 bits of status byte: |
| 31 | +NOTEON = 0x9 |
| 32 | +NOTEOFF = 0x8 |
| 33 | + |
| 34 | +attack = 0.01 # seconds |
| 35 | +release = 0.2 # seconds |
| 36 | + |
| 37 | +fs = None |
| 38 | +voices = {} |
| 39 | + |
| 40 | +client = jack.Client("MIDI-Sine") |
| 41 | +midiport = client.midi_inports.register("midi_in") |
| 42 | +audioport = client.outports.register("audio_out") |
| 43 | +event = threading.Event() |
| 44 | + |
| 45 | + |
| 46 | +def m2f(note): |
| 47 | + """Convert MIDI note number to frequency in Hertz. |
| 48 | +
|
| 49 | + See https://en.wikipedia.org/wiki/MIDI_Tuning_Standard. |
| 50 | +
|
| 51 | + """ |
| 52 | + return 2 ** ((note - 69) / 12) * 440 |
| 53 | + |
| 54 | + |
| 55 | +class Voice: |
| 56 | + def __init__(self, pitch): |
| 57 | + self.time = 0 |
| 58 | + self.time_increment = m2f(pitch) / fs |
| 59 | + self.weight = 0 |
| 60 | + |
| 61 | + self.target_weight = 0 |
| 62 | + self.weight_step = 0 |
| 63 | + self.compare = None |
| 64 | + |
| 65 | + def trigger(self, vel): |
| 66 | + if vel: |
| 67 | + dur = attack * fs |
| 68 | + else: |
| 69 | + dur = release * fs |
| 70 | + self.target_weight = vel / 127 |
| 71 | + self.weight_step = (self.target_weight - self.weight) / dur |
| 72 | + self.compare = operator.ge if self.weight_step > 0 else operator.le |
| 73 | + |
| 74 | + def update(self): |
| 75 | + """Increment weight.""" |
| 76 | + if self.weight_step: |
| 77 | + self.weight += self.weight_step |
| 78 | + if self.compare(self.weight, self.target_weight): |
| 79 | + self.weight = self.target_weight |
| 80 | + self.weight_step = 0 |
| 81 | + |
| 82 | + |
| 83 | +@client.set_process_callback |
| 84 | +def process(frames): |
| 85 | + """Main callback.""" |
| 86 | + events = {} |
| 87 | + buf = memoryview(audioport.get_buffer()).cast('f') |
| 88 | + for offset, data in midiport.incoming_midi_events(): |
| 89 | + if len(data) == 3: |
| 90 | + status, pitch, vel = bytes(data) |
| 91 | + # MIDI channel number is ignored! |
| 92 | + status >>= 4 |
| 93 | + if status == NOTEON and vel > 0: |
| 94 | + events.setdefault(offset, []).append((pitch, vel)) |
| 95 | + elif status in (NOTEON, NOTEOFF): |
| 96 | + # NoteOff velocity is ignored! |
| 97 | + events.setdefault(offset, []).append((pitch, 0)) |
| 98 | + else: |
| 99 | + pass # ignore |
| 100 | + else: |
| 101 | + pass # ignore |
| 102 | + for i in range(len(buf)): |
| 103 | + buf[i] = 0 |
| 104 | + try: |
| 105 | + eventlist = events[i] |
| 106 | + except KeyError: |
| 107 | + pass |
| 108 | + else: |
| 109 | + for pitch, vel in eventlist: |
| 110 | + if pitch not in voices: |
| 111 | + if not vel: |
| 112 | + break |
| 113 | + voices[pitch] = Voice(pitch) |
| 114 | + voices[pitch].trigger(vel) |
| 115 | + for voice in voices.values(): |
| 116 | + voice.update() |
| 117 | + if voice.weight > 0: |
| 118 | + buf[i] += voice.weight * math.sin(2 * math.pi * voice.time) |
| 119 | + voice.time += voice.time_increment |
| 120 | + if voice.time >= 1: |
| 121 | + voice.time -= 1 |
| 122 | + dead = [k for k, v in voices.items() if v.weight <= 0] |
| 123 | + for pitch in dead: |
| 124 | + del voices[pitch] |
| 125 | + return jack.CALL_AGAIN |
| 126 | + |
| 127 | + |
| 128 | +@client.set_samplerate_callback |
| 129 | +def samplerate(samplerate): |
| 130 | + global fs |
| 131 | + fs = samplerate |
| 132 | + voices.clear() |
| 133 | + return jack.SUCCESS |
| 134 | + |
| 135 | + |
| 136 | +@client.set_shutdown_callback |
| 137 | +def shutdown(status, reason): |
| 138 | + print("JACK shutdown:", reason, status) |
| 139 | + event.set() |
| 140 | + |
| 141 | + |
| 142 | +with client: |
| 143 | + print("Press Ctrl+C to stop") |
| 144 | + try: |
| 145 | + event.wait() |
| 146 | + except KeyboardInterrupt: |
| 147 | + print("\nInterrupted by user") |
0 commit comments