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 08 · the notebook from class

What we wrote together in class on 30 October: a scale that knows about octaves, + on clips, a round, a soft sound and two loops that drift. The cleaned-up reference notebook for this lesson is on the course site.

Setup

Last time's tools and Fra Martino.

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 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):
        return self.root + self.distances[degree]

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))

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"

fm = call * 2 >> climb * 2 >> bells * 2
play_clip(fm | rest(8) >> fm, a_major)

Beyond the octave

Degree 7 is the root one octave up, degree -1 the step just below the root: // gives the octave and % the step inside it.

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]
a_major = Scale([2, 2, 1, 2, 2, 2, 1], Pitch("A4"))
a_major[12]
a_major[-3]
a_major[-1]
-1 // 7, -1 % 7
play_clip(note(-3), a_major)

Higher: +

fm + 1 raises a TypeError until Clip knows how to add a number: every degree moves up by n.

@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 __add__(self, n):
        return Clip([(onset, data + n) for onset, data in self.events], self.length)

    def __or__(self, other):              # together
        return Clip(self.events + other.events, max(self.length, other.length))

The clips must be built again with the new class. Fra Martino gets its ending, which reaches below the root.

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 + 2, a_major)

A round in A minor: the second voice enters 8 beats later, 6 degrees higher.

play_clip(fm | rest(8) >> fm + 6, a_minor)

A soft sound

play_clip takes the instrument as a parameter.

def play_clip(clip, scale, beat_s=0.5, instrument=pluck):
    sounds = [(onset * beat_s, instrument(scale[data].f)) for onset, data in clip.events]
    return play(mix_sounds(sounds))

A pad: two sines 0.5 Hz apart, which beat against each other, a slow decay and a slow attack.

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
play_clip(note(0), a_major, 0.5, instrument=pad)

With the whole song the notes overlap and the sum goes beyond 1, so play refuses it.

try:
    play_clip(fm, a_major, 0.5, instrument=pad)
except ValueError as error:
    print(error)

normalize divides by the largest absolute value, so the peak is exactly 1.

def normalize(wave):
    return wave / np.abs(wave).max()
np.abs(np.array([1,2,3,-4])).max()
def play_clip(clip, scale, beat_s=0.5, instrument=pluck):
    sounds = [(onset * beat_s, instrument(scale[data].f)) for onset, data in clip.events]
    return play(normalize(mix_sounds(sounds)))
play_clip(fm + (-7), a_major, 2, instrument=pad)

Loops that drift

play_clip((call + (-7)) * 4 | rest(8) >> (climb * 3), a_major, 1, instrument=pad)

Two loops, 7 and 6 beats long: they start together and drift apart.

first = (call + (-7)) >> rest(3)
second = climb >> rest(2)
play_clip(first * 10 | second * 10, a_major, 1, instrument=pad)

Your turn · Your Fra Martino

Make your own version of Fra Martino in a genre you like, alone or in a group. Keep the tune: the notes of call, climb, bells and ending. Change everything else: the scale or the mode, the tempo, the rhythm, the instruments, the order of the parts. Add any function you need; earlier lessons are fair game, for example the drum kit of lesson 04.

There is no deadline. How to send it: https://actam.bruschi.dev/lesson-08/your-version/