| 1 |
04-simple-midi-synth.py - Create a MIDI synthesizer as a custom class. |
| 2 |
============================================================================================================================================ |
| 3 |
|
| 4 |
|
| 5 |
A more elaborate MIDI synthesizer built in a custom python class. This |
| 6 |
makes easier to use it multiple times. In this example, two objects are |
| 7 |
created, one for the played pitch and another playing one octave lower. |
| 8 |
|
| 9 |
.. code-block:: python |
| 10 |
|
| 11 |
from pyo import * |
| 12 |
from random import random |
| 13 |
|
| 14 |
|
| 15 |
class Synth: |
| 16 |
def __init__(self, transpo=1, mul=1): |
| 17 |
# Transposition factor. |
| 18 |
self.transpo = Sig(transpo) |
| 19 |
# Receive midi notes, convert pitch to Hz and manage 10 voices of polyphony. |
| 20 |
self.note = Notein(poly=10, scale=1, first=0, last=127) |
| 21 |
|
| 22 |
# Handle pitch and velocity (Notein outputs normalized amplitude (0 -> 1)). |
| 23 |
self.pit = self.note["pitch"] * self.transpo |
| 24 |
self.amp = MidiAdsr(self.note["velocity"], attack=0.001, decay=0.1, sustain=0.7, release=1, mul=0.1,) |
| 25 |
|
| 26 |
# Anti-aliased stereo square waves, mixed from 10 streams to 1 stream |
| 27 |
# to avoid channel alternation on new notes. |
| 28 |
self.osc1 = LFO(self.pit, sharp=0.5, type=2, mul=self.amp).mix(1) |
| 29 |
self.osc2 = LFO(self.pit * 0.997, sharp=0.5, type=2, mul=self.amp).mix(1) |
| 30 |
|
| 31 |
# Stereo mix. |
| 32 |
self.mix = Mix([self.osc1, self.osc2], voices=2) |
| 33 |
|
| 34 |
# High frequencies damping. |
| 35 |
self.damp = ButLP(self.mix, freq=5000) |
| 36 |
|
| 37 |
# Moving notches, using two out-of-phase sine wave oscillators. |
| 38 |
self.lfo = Sine(0.2, phase=[random(), random()]).range(250, 4000) |
| 39 |
self.notch = ButBR(self.damp, self.lfo, mul=mul) |
| 40 |
|
| 41 |
def out(self): |
| 42 |
"Sends the synth's signal to the audio output and return the object itself." |
| 43 |
self.notch.out() |
| 44 |
return self |
| 45 |
|
| 46 |
def sig(self): |
| 47 |
"Returns the synth's signal for future processing." |
| 48 |
return self.notch |
| 49 |
|
| 50 |
|
| 51 |
s = Server() |
| 52 |
s.setMidiInputDevice(99) # Open all input devices. |
| 53 |
s.boot() |
| 54 |
|
| 55 |
# Create the midi synth. |
| 56 |
a1 = Synth() |
| 57 |
|
| 58 |
# Send the synth's signal into a reverb processor. |
| 59 |
rev = STRev(a1.sig(), inpos=[0.1, 0.9], revtime=2, cutoff=4000, bal=0.15).out() |
| 60 |
|
| 61 |
# It's very easy to double the synth sound! |
| 62 |
# One octave lower and directly sent to the audio output. |
| 63 |
a2 = Synth(transpo=0.5, mul=0.7).out() |
| 64 |
|
| 65 |
s.gui(locals()) |
| 66 |
|