Group 04

Download .ipynb

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 drumkit import SR, save_wav


# SR = 48000

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

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_waves(waves):
    # size of waves list
    n = len(waves)
    # ensure all waves ar np.array
    waves = [np.asarray(waves[i]) for i in np.arange(n)]
    # do your best to fit
    max_len = max([len(waves[i]) for i in np.arange(n)])
    waves = [np.append(waves[i], np.asarray([0] * (max_len - len(waves[i])))) for i in np.arange(n)]

    return np.sum(waves, 0)

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

def normalize(wave):
    wave = np.asarray(wave)
    return wave / np.abs(wave).max()

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 __add__(self, n):
        # just return global length parameter
        # and apply transposition to each data part of all the events
        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))

# wrappers for convenient Clip construction
def note(data, length=1):
    return Clip([(0, data)], length)

def rest(length):
    return Clip([], length)

# let us express clips in terms of grades of a scale
# = higher musical abstraction
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):
        # extract also octave information before python default wrapping of getitem
        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, instrument=pluck):
    return play(render_clip(clip, scale, beat_s, instrument))

def render_clip(clip, scale, beat_s= 0.5, instrument = pluck):
    sounds = [(onset * beat_s, instrument(scale[data].f)) for onset, data in clip.events]
    return normalize(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"
ending = note(0) >> note(-3) >> note(0, 2)


fm = call * 2 >> climb * 2 >> bells * 2 >> ending * 2
play_clip(fm | rest(8) >> (fm + 4), a_major)
def pad(f, dur_s=3, tau=0.35, attack=0.2, amplitude=0.2):
    harmonics = [1.5, 2, 3, 5, 8, 11]
    harmonics_weight = [1 / (i + 1) for i in range(len(harmonics) - 1)] + [0.1]
    return voice(f, dur_s, tau, attack, amplitude, 1, harmonics, harmonics_weight)

def pad_2(f, dur_s = 10, tau = 0.9, attack = 3, amplitude = 0.7):
    harmonics = [1.5, 2, 3, 4.2, 5]
    harmonics_weight = [0.7 / (i + 1) for i in range(len(harmonics))]
    return voice(f, dur_s, tau, attack, amplitude, 0.4, harmonics, harmonics_weight)

def trumpet(f, dur_s = 6, tau = 0.8, attack = 0.1, amplitude = 0.7):
    # f = f / 2
    harmonics =        np.array([1.3,   2,   3,   4,   5,   6,   7,   8,   10])
    harmonics_weight = np.array([0.05, 0.1, 0.6, 0.7, 0.9, 0.7, 0.45, 0.2,  0.2])
    harmonics_weight = harmonics_weight * np.asarray([1 / (i + 1) for i in range(len(harmonics_weight))])

    return voice(f, dur_s, tau, attack, amplitude, 7, harmonics, harmonics_weight)

def voice(f, dur_s = 6, tau = 0.8, attack = 0.1, amplitude = 0.7, mod_f = 0.001, harmonics = [], harmonics_weight = []):
    # define time domain
    t = np.arange(round(dur_s * SR)) / SR

    # define attack and decay envelopes
    env = np.exp(-t / tau)
    rise = np.minimum(1, t ** 2 / attack)

    # compute wave and apply modulation with beatings
    wave = np.sin(2 * np.pi * f * t)
    wave_mod = np.sin(2 * np.pi * (f + mod_f) * t)
    wave = (wave + wave_mod) * 0.6

    # define harmonics as columns to achieve matrix computation
    wave_harmonics = np.asarray([])
    if len(harmonics) > 0:
        harmonics =        np.asarray(harmonics)
        harmonics = harmonics[:, None]
        harmonics_weight = np.asarray(harmonics_weight)
        harmonics_weight = harmonics_weight[:, None]
        # apply f as factor
        harmonics = f * harmonics
    
        # compute phases matrix
        harmonics_phases = harmonics * t
        # compute values
        wave_harmonics = harmonics_weight * np.sin(2 * np.pi * harmonics_phases)

    # sum
    wave = wave + np.sum(wave_harmonics, 0)

    # return with amplitude and envelopes
    return amplitude * env * wave * rise
# loop = note(0) >> note(4) >> note(3) >> note(4) >> note(6, 2)
# play_clip((loop | rest(4) >> loop) * 10, a_major, 0.3, instrument = pad)

beat_s = 0.95
little_chord = note(0, 2) | note(-5, 3) | note(-7, 4)
solo = (note(0, 2) | note(0,2) >> note(5) >> note(4)) * 2 >> note (6, 1) >> note(4, 3)

fj =           render_clip(call * 2 >> climb * 2 >> bells * 2 >> ending * 2,     a_major, beat_s,     pad)
background =   render_clip((call + -5) * 2 >> (climb + -5) >> little_chord,      a_major, beat_s * 3, pad_2)
bk_2 =         render_clip((call + -9) * 2 >> (bells + -9) >> note(-11),         a_major, beat_s * 3, pad_2)   * 0.7
tpt =          render_clip(rest(12) >> solo,                                     a_major, beat_s * 2, trumpet) * 1.2

fjs_funeral_march_with_hope = normalize(mix_waves([fj, background, bk_2, tpt]))
# play(fjs_funeral_march_with_hope)
# just stuff to work out how to write the functions....

t = np.arange(round(0.0001 * 48000)) / 48000
harmonics = 440 * np.array([2, 4, 5])
harmonics = harmonics[:, None]

print(f"Shape of time: {t.shape}, of harmonics: {harmonics.shape}")

phases = harmonics * t
sins = np.sin(2 * np.pi * phases)

print(phases)
print(f"phases[0, 1] is \t{phases[0, 1]}")
print(f"sins[0, 1] is \t\t{sins[0, 1]}")

sums = np.sum(sins, 0)
print(sums)

weight = 440 / harmonics
print(weight)
print(weight * sins)

pepper = np.arange(100)
chili = np.arange(10)

# print(chili + pepper)
# save and play
import ast
import json
import math
from pathlib import Path
import sys

save_wav("frere jacques' funeral march with hope.wav", fjs_funeral_march_with_hope, SR)
play(fjs_funeral_march_with_hope)