This notebook comes from outside the course materials: it is shown here to read, not to run.
from IPython.display import Audio
from dataclasses import dataclass
import numpy as np
from matplotlib import pyplot as plt
SR = 48000
def play(wave):
return Audio(wave, rate=SR, normalize=False, autoplay=False)
def pluck(f, dur_s=1.0, tau=0.3, amplitude=0.25):
t = np.arange(round(dur_s * SR)) / SR
env = np.exp(-t / tau)
wave = np.sin(2 * np.pi * f * t)
return amplitude * env * wave
def normalize(wave):
return wave / np.abs(wave).max()
def mix_sounds(sounds): # a sound is (onset_s, wave)
dur_s = max([onset_s + len(wave) / SR for onset_s, wave in sounds])
out = np.zeros(round(dur_s * SR))
for onset_s, wave in sounds:
onset = round(onset_s * SR)
out[onset:onset + len(wave)] += wave
return out
note_names = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
class Pitch:
def __init__(self, value):
if isinstance(value, str): # a name like "C4": the octave last, the note before
value = 12 * (int(value[-1]) + 1) + note_names.index(value[:-1])
self.midi = value
@property
def f(self): # the frequency in Hz
return 440 * 2 ** ((self.midi - 69) / 12)
def __add__(self, semitones):
if isinstance(semitones, Pitch):
raise TypeError("Add semitones, not a pitch.")
return Pitch(self.midi + semitones)
def __sub__(self, other):
if isinstance(other, Pitch):
return self.midi - other.midi # an interval
return Pitch(self.midi - other) # a lower pitch
def __eq__(self, other):
return isinstance(other, Pitch) and self.midi == other.midi
def __repr__(self):
return note_names[self.midi % 12] + str(self.midi // 12 - 1)
@dataclass
class Clip:
events: list # (onset, data): onset in beats
length: float # in beats: where the next clip starts
def __rshift__(self, other): # then
moved = [(onset + self.length, data) for onset, data in other.events]
return Clip(self.events + moved, self.length + other.length)
def __mul__(self, times): # again
out = Clip([], 0)
for _ in range(times):
out = out >> self
return out
def __or__(self, other): # together
return Clip(self.events + other.events, max(self.length, other.length))
def note(data, length=1):
return Clip([(0, data)], length)
def rest(length):
return Clip([], length)
class Scale:
def __init__(self, steps, root):
self.root = root
self.distances = []
distance = 0
for step in steps:
self.distances.append(distance)
distance += step
def __getitem__(self, degree):
octave = degree // len(self.distances)
step = degree % len(self.distances)
return self.root + (12 * octave) + self.distances[step]
def play_clip(clip, scale, beat_s=0.5):
sounds = [(onset * beat_s, pluck(scale[data].f)) for onset, data in clip.events]
return play(mix_sounds(sounds))
def crea_clip(clip, scale, beat_s=0.5):
sounds = [(onset * beat_s, pluck(scale[data].f)) for onset, data in clip.events]
return mix_sounds(sounds)
def crea_clip_instr(clip, scale, beat_s=0.5, instrument=pluck):
sounds = [(onset * beat_s, instrument(scale[data].f)) for onset, data in clip.events]
return mix_sounds(sounds)
def pad(f, dur_s=10.0, tau=4, amplitude=0.25, attack=3):
t = np.arange(round(dur_s * SR)) / SR
env = np.exp(-t / tau)
wave1 = np.sin(2 * np.pi * f * t)
wave2 = np.sin(2 * np.pi * (f + 0.5) * t)
wave = wave1 + wave2
rise = np.minimum(1, t/attack)
return amplitude * env * wave * rise
def square_wave(f=440, duration=0.5, amplitude=0.15, sample_rate=48_000):
half_period = round(sample_rate / (2 * f))
period = [-amplitude] * half_period + [amplitude] * half_period
sample_count = round(duration * sample_rate)
repeats = (sample_count + len(period) - 1) // len(period)
return (period * repeats)[:sample_count]
from math import sin, pi
def sine_wave(f=440, 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))]
a_major = Scale([2, 2, 1, 2, 2, 2, 1], Pitch("A4"))
a_minor = Scale([2, 1, 2, 2, 1, 2, 2], Pitch("A4"))
call = note(0) >> note(1) >> note(2) >> note(0) # "Frère Jacques"
climb = note(2) >> note(3) >> note(4, 2) # "dormez-vous?"
bells = note(4, 0.5) >> note(5, 0.5) >> note(4, 0.5) >> note(3, 0.5) >> note(2) >> note(0) # "sonnez les matines"
ending = note(0) >> note(-3) >> note(0, 2)
fm = call * 2 >> climb * 2 >> bells * 2 >> ending * 2
play_clip(fm >> fm, a_major)
"""The lesson 04 drum kit.
Every function below comes from the lesson 04 notebook, except the two
helpers at the end (ring_track and save_wav).
"""
from math import exp
from random import random
import struct
import wave
SR = 48000
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 noise(duration=0.05, amplitude=0.15, sample_rate=SR):
n = round(duration * sample_rate)
return [amplitude * (2 * random() - 1) for _ in range(n)]
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 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 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 closed_hat(duration=0.06, tau=0.010, amplitude=0.15, sample_rate=SR):
source = noise(duration, amplitude=amplitude, sample_rate=sample_rate)
shape = envelope_exp(duration, tau=tau, sample_rate=sample_rate)
return edge_fade(vca(source, shape), sample_rate=sample_rate)
def open_hat(duration=0.30, tau=0.070, amplitude=0.15, sample_rate=SR):
source = noise(duration, amplitude=amplitude, sample_rate=sample_rate)
shape = envelope_exp(duration, tau=tau, sample_rate=sample_rate)
return edge_fade(vca(source, shape), sample_rate=sample_rate)
def kick_raw(
duration=0.25, start_hz=180, end_hz=45,
pitch_tau=0.025, amp_tau=0.060,
amplitude=0.20, sample_rate=SR,
):
pitch_shape = envelope_exp(duration, tau=pitch_tau, sample_rate=sample_rate)
pitch = [end_hz + (start_hz - end_hz) * value for value in pitch_shape]
body = square_wave_f(pitch, sample_rate=sample_rate, amplitude=amplitude)
shape = envelope_exp(duration, tau=amp_tau, sample_rate=sample_rate)
return vca(body, shape)
def kick(
duration=0.25, start_hz=180, end_hz=45,
pitch_tau=0.025, amp_tau=0.060,
amplitude=0.20, sample_rate=SR,
):
wave = kick_raw(
duration=duration, start_hz=start_hz, end_hz=end_hz,
pitch_tau=pitch_tau, amp_tau=amp_tau,
amplitude=amplitude, sample_rate=sample_rate,
)
return edge_fade(wave, sample_rate=sample_rate)
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 snare(
duration=0.20, amplitude=0.15, noise_gain=0.5,
sample_rate=SR,
):
pitch = [
180 + 120 * value
for value in envelope_exp(duration, tau=0.010, sample_rate=sample_rate)
]
body = vca(
square_wave_f(pitch, amplitude=amplitude, sample_rate=sample_rate),
envelope_exp(duration, tau=0.025, sample_rate=sample_rate),
)
wires = vca(
noise(duration, amplitude=amplitude, sample_rate=sample_rate),
envelope_exp(duration, tau=0.055, sample_rate=sample_rate),
)
return edge_fade(
mix(body, wires, ga=1.0, gb=noise_gain),
sample_rate=sample_rate,
)
def fit(wave, n_samples):
padding = max(0, n_samples - len(wave))
return wave[:n_samples] + [0] * padding
def read_pattern(pattern):
steps = []
for symbol in pattern:
if symbol == "x":
steps.append(1)
elif symbol == ".":
steps.append(0)
else:
raise ValueError("Use only x for a hit and . for a rest.")
return steps
def render_pattern(pattern, instrument, step_s, sample_rate=SR):
n = round(step_s * sample_rate)
steps = read_pattern(pattern)
slots = []
for hit in steps:
if hit == 1:
wave = instrument(sample_rate=sample_rate)
else:
wave = []
slots.append(fit(wave, n))
return sum(slots, [])
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
def render_track(track, sample_rate=SR):
pattern, instrument, step_s = track
return render_pattern(pattern, instrument, step_s, sample_rate=sample_rate)
def render_tracks(tracks, sample_rate=SR):
waves = [render_track(track, sample_rate=sample_rate) for track in tracks]
return mix_tracks(waves)
def render_timed_pattern(pattern, instrument, step_lengths, sample_rate=SR):
steps = read_pattern(pattern)
if len(steps) != len(step_lengths):
raise ValueError("Give each pattern step one slot length.")
slots = []
for hit, n in zip(steps, step_lengths):
if hit == 1:
wave = instrument(sample_rate=sample_rate)
else:
wave = []
slots.append(fit(wave, n))
return sum(slots, [])
def render_timed_tracks(tracks, sample_rate=SR):
waves = []
for pattern, instrument, step_lengths in tracks:
wave = render_timed_pattern(
pattern, instrument, step_lengths, sample_rate=sample_rate
)
waves.append(wave)
return mix_tracks(waves)
# --- Not in the notebook -------------------------------------------------
def ring_track(pattern, instrument, step_samples):
"""Turn a pattern into a timed track whose hits ring until the next hit.
render_pattern cuts every hit to one step. Here each slot lasts until the
next "x" of the same track, so long sounds keep their tails.
Use the result with render_timed_tracks.
"""
hits = ""
lengths = []
for symbol in pattern:
if symbol == "x":
hits = hits + "x"
lengths.append(step_samples)
elif symbol == ".":
if len(lengths) == 0:
hits = "."
lengths.append(0)
lengths[-1] = lengths[-1] + step_samples
else:
raise ValueError("Use only x for a hit and . for a rest.")
return (hits, instrument, lengths)
def save_wav(path, wave_samples, sample_rate=SR):
"""Write a mono 16-bit WAV. Refuses to clip instead of normalising."""
peak = max(abs(x) for x in wave_samples)
if peak > 1:
raise ValueError(f"Peak {peak:.2f} exceeds 1: lower the gains.")
with wave.open(str(path), "wb") as f:
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(sample_rate)
f.writeframes(struct.pack(
"<" + "h" * len(wave_samples),
*(round(x * 32767) for x in wave_samples),
))
def read_accents(pattern):
gains = []
for symbol in pattern:
if symbol == "x":
gains.append(0.5)
elif symbol == "X":
gains.append(1.0)
elif symbol == ".":
gains.append(0.0)
else:
raise ValueError("Use only x, X and . in an accented pattern.")
return gains
def render_accents(pattern, instrument, step_s, sample_rate=SR):
n = round(step_s * sample_rate)
gains = read_accents(pattern)
slots = []
for gain in gains:
if gain > 0:
hit = instrument(sample_rate=sample_rate)
wave = [gain * sample for sample in hit]
else:
wave = []
slots.append(fit(wave, n))
return sum(slots, [])
def render_accent_tracks(tracks, sample_rate=SR):
waves = []
for pattern, instrument, step_s in tracks:
wave = render_accents(pattern, instrument, step_s, sample_rate=sample_rate)
waves.append(wave)
return mix_tracks(waves)
a_major = Scale([2, 2, 1, 2, 2, 2, 1], Pitch("C#4"))
a_minor = Scale([2, 1, 2, 2, 1, 2, 2], Pitch("C#4"))
call = note(0) >> note(1) >> note(2) >> note(0) # "Frère Jacques"
climb = note(2) >> note(3) >> note(4, 2) # "dormez-vous?"
bells = note(4, 0.5) >> note(5, 0.5) >> note(4, 0.5) >> note(3, 0.5) >> note(2) >> note(0) # "sonnez les matines"
ending = note(0) >> note(-3) >> note(0, 2)
fm = call * 2 >> climb * 2 >> bells * 2 >> ending * 2
melodia = crea_clip_instr(fm, a_minor, 0.4, pluck) #32 totali
melodia_lowvol = melodia * 0.75
fastphrase = note(7,0.5) >> note(8,0.5) >> note(9,0.5) >> note(14,0.5) >> note(7,0.25) >> note(8,0.25) >> note(9,0.25) >> note(7,0.25) >> note(7,0.25) >> note(4,0.25) >> note(7,0.5)>>note(14,0.5) >> note(15,0.5) >> note(16,0.5) >> note(21,0.5) >> note(14,0.25) >> note(15,0.25) >> note(16,0.25) >> note(14,0.25) >> note(14,0.25) >> note(11,0.25) >> note(14,0.5) # "Frère Jacques"
highpitch = (crea_clip_instr(fastphrase * 4, a_minor, 0.4, pluck))*0.25
mel2_lowvol = (crea_clip_instr(call *8, a_minor, 0.4, pluck))* 0.75
#bassline = note(-14,1.5) >> note(-14, 1.5)>> note(-14, 2)>> note(-14, 1.5)>> note(-9, 1.5) >> note(-14,1.5) >> note(-14, 1.5)>> note(-14, 2)>> note(-7, 1.5)>> note(-9, 1.5)
bassline = note(-21,1.5) >> note(-21, 1.5)>> note(-21, 2)>> note(-21, 1.5)>> note(-16, 1.5) >> note(-21,1.5) >> note(-21, 1.5)>> note(-21, 2)>> note(-14, 1.5)>> note(-16, 1.5)
bass_mel = 0.30*(crea_clip_instr(bassline, a_minor, 0.4, square_wave))
ultimanota_bassline = note(-21,4)
ultimanota_bassline_mel = 0.30* (crea_clip_instr(ultimanota_bassline, a_minor, 0.4, square_wave))
bpm = 150
step_s = 60 / bpm / 8
nokick = [
("................X...................x...........X...........x...................X...........x.......x...........X...........X.x.", snare, step_s),
("X...x...X.x.X.x.X...x...X...XXx.x.X.x...X.x.X.x.X...x...X...XxxxX...x...X.x.X.x.X...x...X...XXx.x.X.x...X.x.X.x.X...x...X...Xxxx", closed_hat, step_s),
]
tracks = [
("X...........X...........X...............X...........X...........X...........X...........X...............X...........X.....X.....", kick, step_s),
("................X...................x...........X...........x...................X...........x.......x...........X...........X.x.", snare, step_s),
("X...x...X.x.X.x.X...x...X...XXx.x.X.x...X.x.X.x.X...x...X...XxxxX...x...X.x.X.x.X...x...X...XXx.x.X.x...X.x.X.x.X...x...X...Xxxx", closed_hat, step_s),
]
intro_tracks = [
("........................................................................................................X...........X.....X.....", kick, step_s),
("....................................................................................................x...........X...........X.x.", snare, step_s),
("............................................................................................XXx.x.X.x...X.x.X.x.X...x...X...Xxxx", closed_hat, step_s),
]
pattern_drums = (tracks)
drums = (render_accent_tracks(pattern_drums))
intro_drums = (render_accent_tracks(intro_tracks))
nokick_drums = (render_accent_tracks(nokick))
canzone = normalize((mix_sounds([(step_s*8*32, highpitch),(step_s*8*32, melodia_lowvol),(step_s*8*64, ultimanota_bassline_mel),(step_s * 8 * 16,intro_drums),(0,melodia_lowvol), (step_s * 8 * 32, nokick_drums), (step_s * 8 * 48, drums),(step_s * 8 * 32,bass_mel),(step_s * 8 * 48,bass_mel)])))