Notebook from class

Download .ipynb Open in the browser

“Open in the browser” runs the notebook on your computer with JupyterLite: no installation, no account. Your changes stay in that browser: download the notebook to keep them.

Lesson 05 · the notebook from class

What we wrote together in class on 9 October: a softer tone, a sine wave, an arpeggio, events, tanh and a decaying synth. The cleaned-up reference notebook for this lesson is on the course site.

Setup

SR = 48000

from math import exp
from IPython.display import Audio
from matplotlib import pyplot as plt

def play(wave, sample_rate=SR):
    return Audio(wave, rate=sample_rate, normalize=False, autoplay=False)

def square_wave_f(f, sample_rate=SR, amplitude=0.15):
    phase = 0.0
    wave = []
    for frequency in f:
        if not 0 < frequency < sample_rate / 2:
            raise ValueError("Each frequency must be positive and below half the sample rate.")
        wave.append(-amplitude if phase < 0.5 else amplitude)
        phase = (phase + frequency / sample_rate) % 1
    return wave

def envelope_exp(duration=0.05, tau=0.012, sample_rate=SR):
    if tau <= 0:
        raise ValueError("tau must be positive.")
    n = round(duration * sample_rate)
    return [exp(-(i / sample_rate) / tau) for i in range(n)]

def vca(wave, signal):
    if len(wave) != len(signal):
        raise ValueError("The sound and control signal must have equal lengths.")
    return [x * gain for x, gain in zip(wave, signal)]

def edge_fade(wave, attack=0.001, release=0.005, sample_rate=SR):
    n = len(wave)
    attack_samples = max(1, round(attack * sample_rate))
    release_samples = max(1, round(release * sample_rate))
    edge = [
        min(1.0, i / attack_samples, (n - 1 - i) / release_samples)
        for i in range(n)
    ]
    return vca(wave, edge)

def mix(a, b, ga=1.0, gb=1.0):
    if len(a) != len(b):
        raise ValueError("Pad the shorter sound with silence before mixing.")
    return [ga * x + gb * y for x, y in zip(a, b)]

def fit(wave, n_samples):
    padding = max(0, n_samples - len(wave))
    return wave[:n_samples] + [0] * padding

def gain(wave, g=1.0):
    return [g * x for x in wave]

def peak(wave):
    return max([abs(x) for x in wave])

Filtering a square wave

sw = square_wave_f([440 for _ in range(SR*1)])
play(sw)
def lp(wave):

    y = [0]*len(wave)
    y[0] = wave[0]
    for i in range(1, len(wave)):
        y[i] = y[i-1] + 0.9 * (wave[i-1] - y[i-1])

    return y
play(lp(sw))

What remains if we subtract the filtered wave from the original? The fast changes: a high-pass filter.

hpwave = [x - y for x, y in zip(sw, lp(sw))]
play(hpwave)

A sine wave

from math import sin, pi
sin(0)
sin(pi)
sin(pi/2)

sin of the sample index, one radian per sample: which frequency is this?

tone_samples = [sin(x) for x in range(SR)]
play(tone_samples)

We want one full cycle (2π) every period T = 1/f, that is every T * SR samples.

# 440 hz
# T = 1/f
# n = T*SR
# a*T*SR == 2*pi
f = 440
T = 1/f
a = (2*pi)/(T*SR)
tone_samples = [sin(a*x) for x in range(SR)]
play(tone_samples)
def sine_wave(f, duration=0.5, sample_rate=SR):
    T = 1/f
    a = (2*pi)/(T*sample_rate)
    return [sin(a*x) for x in range(round(sample_rate*duration))]

Notes and an arpeggio

def note_pitch(semitones, root=440):
    return root*2**(semitones/12)
play(sine_wave(note_pitch(0)) + sine_wave(note_pitch(2)))

The Em7 arpeggio of Weird Fishes/Arpeggi: E3 is 17 semitones below A4, and the guitar picks the minor seventh, the minor third and the root.

melody_notes = [edge_fade(sine_wave(note_pitch(x, root=note_pitch(-17)),0.2)) for x in [10, 3, 0]]
play(sum(melody_notes,[]))
arpeggio1 = [edge_fade(sine_wave(note_pitch(x, root=note_pitch(-17)),0.2)) for x in [10, 3, 0]*8]
arpeggio2 = [edge_fade(sine_wave(note_pitch(x, root=note_pitch(-15)),0.2)) for x in [10, 3, 0]*8]
play(sum(arpeggio1+arpeggio2, []))

Events: a time and a sound

def my_synth(x, duration=0.2, root=note_pitch(-17)):
    return edge_fade(sine_wave(note_pitch(x, root),duration))
play(my_synth(0))
play(my_synth(10,1))
event1 = (0, my_synth(10, 1))
event2 = (0.2, my_synth(3, 1))
event3 = (0.4, my_synth(0, 1))
def render_event(event, sample_rate=SR):
    return [0]*(round(SR*event[0])) + event[1]
play(render_event(event3))
def mix_tracks(waves):
    if len(waves) == 0:
        return []
    longest = max([len(wave) for wave in waves])
    result = [0] * longest
    for wave in waves:
        result = mix(result, fit(wave, longest))
    return result
a1 = mix_tracks([render_event(e) for e in [event1, event2, event3]])

Three overlapping notes at full amplitude go beyond ±1, and the player refuses them:

# play(a1)  # ValueError: Audio data must be between -1 and 1 when normalize=False
max(a1)

Squashing with tanh

from math import tanh
tanh(0)
tanh(10**20)
tanh(-10**20)
plt.plot([tanh(x/100) for x in range(-1000,1000)])
max([tanh(x) for x in a1])
min([tanh(x) for x in a1])
play([tanh(x) for x in a1])

A decaying synth

An exponential envelope makes each note fade, as a plucked string does.

def my_synth2(x, duration=0.6, root=note_pitch(-17)):
    wave = edge_fade(sine_wave(note_pitch(x, root),duration))
    wave = vca(envelope_exp(duration, 0.5), wave)
    return wave
play(my_synth2(0))
event1 = (0, my_synth2(10, 0.6))
event2 = (0.2, my_synth2(3, 0.6))
event3 = (0.4, my_synth2(0, 0.6))
a2 = mix_tracks([render_event(e) for e in [event1, event2, event3]])
max(a2)
play([tanh(0.1*x) for x in a2])