Group 02

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
from drumkit import *

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 __add__(self, n):
        return Clip([(onset, data + n) for onset, data in self.events], self.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 distorted_808(f, dur_s=1.5, tau=0.5, amplitude=0.25, drive=12.0, asym=0.2, glide_st=12, glide_tau=0.03, attack=0.002):
    
    n = round(dur_s * SR)
    t = np.arange(n) / SR

    # Pitch envelope
    f_inst = f * 2 ** (glide_st * np.exp(-t / glide_tau) / 12)
    phase = 2 * np.pi * np.cumsum(f_inst) / SR
    wave = np.sin(phase)

    # Distort
    x = np.tanh(drive * (wave + asym))
    x -= x.mean()
    x /= np.max(np.abs(x))

    # Envelope
    env = (1 - np.exp(-t / attack)) * np.exp(-t / tau)
    x *= env

    # fade-out
    fade = min(n, round(0.01 * SR))
    x[n - fade:] *= np.linspace(1, 0, fade)

    return amplitude * x

def normalize(wave):
    return wave / np.abs(wave).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)))

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

def mix(a, b, ga=1.0, gb=1.0):
    return [ga * x + gb * y for x, y in zip(a, b)]
    
    
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, 1.5) >> note(1, 0.5) >> note(2) >> note(0)                                     
climb = note(2, 1.5) >> note(3, 0.5) >> note(4, 2)  
bells = note(4, 0.75) >> note(5, 0.25) >> note(4, 0.5) >> note(3, 0.5) >> note(2) >> note(0)   
end = note(0) >> note(-3) >> note(0,2)

song = call * 2 >> climb * 2 >> bells * 2 >> end * 2

play_clip(song + (-23), a_minor, 120/130, distorted_808)
bpm = 130
step_s = 60 / bpm / 4
#           1 e & a 2 e & a 3 e & a 4 e & a 1 e & a 2 e & a 3 e & a 4 e & a
tracks = [('x...........x...x.............x.x...........x...x...............',kick,step_s),
          ('........x...............x...............x...............x.......',snare,step_s),
          ('x.xxx.x.x.x.x.x.x.x.x.x.x.x.x.x.x.xxx.x.x.x.x.x.x.x.x.x.x.x.x.x.',closed_hat,step_s),
          ('................................................................',open_hat,step_s)]

beat = render_tracks(tracks)*4

play(beat)
eightoeight = get_clip(song + (-23), a_minor, 120/130, distorted_808)

play(normalize(mix(beat, eightoeight)))