Group 01

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 matplotlib import pyplot as plt

SR = 48000

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

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

def pluck(f, dur_s=1.0, tau=0.3, amplitude=0.45):
    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 pad(f, dur_s=10, tau=8, amplitude=0.25):
    atk = 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+2) * t)
    rise = np.minimum(1, t / atk)
    return amplitude * env * (wave1+wave2) *rise

def pad_2(f, dur_s=4, tau=4, amplitude=0.10):
    atk = 3
    t = np.arange(round(dur_s * SR)) / SR
    env = np.exp(-t / tau)
    wave1 = np.sin(2 * np.pi * f * t)
    rise = np.minimum(1, 1.1*t / atk)
    return amplitude * env * (wave1) *rise

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 mix_clips(clips_to_mix):
    events = []
    dur_beats = 0
    
    for onset_beats, clip in clips_to_mix:
        shifted_events = [(onset + onset_beats, data) for onset, data in clip.events]
        events.extend(shifted_events)
        
        dur_beats = max(dur_beats, onset_beats + clip.length)
        
    events.sort(key=lambda e: e[0])    
    return Clip(events, dur_beats)

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__():
        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))

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):
        scale_length = len(self.distances)
        octaves = degree // scale_length
        step = degree % scale_length
        return self.root + self.distances[step] + (12 * octaves)

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

def play_tracks(tracks, scale, beat_s=0.3):
    all_sounds = []
    
    for clip, instrument in tracks:
        track_sounds = [(onset * beat_s, instrument(scale[data].f)) for onset, data in clip.events]
        all_sounds.extend(track_sounds)
        
    return play(mix_sounds(all_sounds))

a_major = Scale([2, 2, 1, 2, 2, 2, 1], Pitch("B3"))
a_minor = Scale([2, 1, 2, 2, 1, 2, 2], Pitch("B3"))
chromatic_e = Scale([1] * 12, Pitch("E3"))

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

cfh_1 = note(0)>>note(3)>>note(0)>>note(3)>>note(5)>>note(3)>>note(5)>>note(3)>>note(6)>>note(3)>>note(5)>>note(3)>>note(7)>>note(10)>>note(12, 2)
cfh_2 = note(0)>>note(3)>>note(0)>>note(3)>>note(5)>>note(3)>>note(5)>>note(3)>>note(6)>>note(5)>>note(3)>>note(0, 4)

cfh_3 = note(0, 1)>>note(0, 2)>>note(0,2)>>note(0, 2)>>note(0, 2)>>note(0, 2)>>note(0, 1)>>note(7)>>note(10)>>note(12, 2)
cfh_4 = note(0, 1)>>note(0, 2)>>note(0,2)>>note(0, 2)>>note(0, 2)>>note(0, 2)>>note(0, 1)>>note(6, 1)>>note(5)>>note(3)>>note(0, 2)

cfh = cfh_1 * 3 >> cfh_2 >> cfh_3 * 3 >> cfh_4 #>> climb * 2 >> bells * 2
#play_clip(fm | rest(8) >> fm, chromatic_e)
play_clip(cfh, chromatic_e,0.15, instrument = pluck)
#play_clip(fm, a_major, 0.5, instrument = pad)
#COWBOYS FROM HELLL
first = (call) >> rest(3)
second = climb>>rest(2)
play_clip(first*10 | second * 10, a_major, 1, instrument=pad)
#play_clip(cfh, chromatic_e, 0.2, instrument=pad)
bla = note(0)>>note(3)>>note(0)>>note(3)>>note(5)>>note(3)>>note(5)>>note(3)
ble =note(12)>>note(15)>>note(12)>>note(15)>>note(17)>>note(15)>>note(17)>>note(15)
blauer = mix_clips([(0,bla),(0,ble)]) *40
#play_clip(blauer, a_major, .2, instrument=pad_2)


harp = note(12, 0.5)>>note(10, .5)>>note(9, .5)>>note(10, .5)>>note(9, .5)>>note(7,.5)>>note(9,.5)>>note(7,.5)>>note(5,.5)>>note(7,.5)>>note(5,.5)
harp = rest(10)>>harp*30
#play_clip(harp, a_major, .3, instrument=pluck)
play_tracks([(cfh,pad),(blauer,pad_2),(harp,pluck)], a_major)