Files

780 lines
30 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
"""
EXIT PROGRESSIVE EMULATION - Schranz / industrial techno, 150 BPM, F minor, 320 bars.
Generates (stdlib only, deterministic):
exit-progressive-emulation.dawproject open Bitwig/DAWproject file (tracks + arrangement clips)
midi/full_arrangement.mid all tracks, one SMF type 1 file
midi/NN_<track>.mid one full-length MIDI file per track
Usage: python3 build_track.py [--devices] [--no-automation] [--no-vocal]
--devices add instrument-device hints to each track
--no-automation leave out the filter automation and kick-ducking (bare note tracks)
--no-vocal leave out the TTS vocal audio track
"""
import os
import random
import struct
import sys
import wave
import zipfile
from xml.sax.saxutils import quoteattr
HERE = os.path.dirname(os.path.abspath(__file__))
TITLE = "Exit Progressive Emulation"
BPM = 150
PPQ = 960
TOTAL_BARS = 320
CHUNK = 8 # bars per arrangement clip
# Vocal (TTS) audio clip, rendered at 140 BPM by vocal/make_vocal.py. It is placed UNWARPED
# (original speed, clip content in seconds) so it keeps its own 140 BPM feel against the 150 BPM track.
VOCAL_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "vocal", "when_you_change_140bpm.wav")
VOCAL_BARS = [128, 184] # 0-based start bars: Breakdown opening, and the final riser into Drop 2
VOCAL_COLOR = "#c77dff"
VOCAL_VOLUME = 0.75
SECTIONS = [ # name, start bar, length
("Intro", 0, 32),
("Build 1", 32, 32),
("Drop 1", 64, 64),
("Breakdown", 128, 32),
("Build 2", 160, 32),
("Drop 2", 192, 96),
("Outro", 288, 32),
]
def section_at(bar):
for name, start, length in SECTIONS:
if start <= bar < start + length:
return name, bar - start, length
raise ValueError(bar)
# ---------------------------------------------------------------- harmony (F minor)
# chord index: 0 = Fm (i), 1 = Db (VI), 2 = Eb (VII), 3 = Cm (v)
BASS_ROOT = {0: 29, 1: 25, 2: 27, 3: 24} # F1, Db1, Eb1, C1
CHORDS = {
0: [53, 56, 60, 63], # Fm7 F3 Ab3 C4 Eb4
1: [49, 53, 56, 60], # Dbmaj7 Db3 F3 Ab3 C4
2: [51, 55, 58, 62], # Ebmaj7 Eb3 G3 Bb3 D4
3: [48, 51, 55, 58], # Cm7 C3 Eb3 G3 Bb3
}
PROG_A = [0, 0, 0, 0, 1, 1, 2, 3]
PROG_B = [0, 0, 2, 2, 1, 1, 3, 3]
def prog(sec, b):
if sec == "Breakdown":
return (b // 4) % 4
if sec == "Drop 2" and (b // 8) % 2 == 1:
return PROG_B[b % 8]
return PROG_A[b % 8]
def jitter(rng, amount=0.004):
return rng.uniform(-amount, amount)
def roll(n, key, t0, length, sp0, sp1, v0, v1, dur=0.6):
"""Accelerating roll from sp0 to sp1 hits-per-beat over `length` beats."""
t = t0
while t < t0 + length - 1e-9:
f = (t - t0) / length
sp = sp0 + (sp1 - sp0) * f
gap = 1.0 / sp
n.append((t, gap * dur, key, v0 + (v1 - v0) * f))
t += gap
# ---------------------------------------------------------------- tracks
def gen_kick(rng):
n = []
for bar in range(TOTAL_BARS):
sec, b, _ = section_at(bar)
t0 = bar * 4.0
if sec == "Breakdown":
continue
def hit(beat, vel=1.0, dur=0.95):
n.append((t0 + beat, dur, 36, vel))
if sec in ("Intro", "Build 1"):
for k in range(4):
hit(k)
elif sec in ("Drop 1", "Drop 2"):
if b % 8 == 7: # pickup kick
for k in range(3):
hit(k)
hit(3.0, 1.0, 0.45)
hit(3.5, 0.85, 0.45)
else:
for k in range(4):
hit(k)
elif sec == "Build 2":
if b < 16:
hit(0, 0.9, 1.9)
hit(2, 0.9, 1.9)
elif b < 28:
for k in range(4):
hit(k)
elif b < 31:
for i in range(8):
hit(i * 0.5, 0.75 + 0.25 * (b - 28) / 3, 0.45)
else:
for i in range(12):
hit(i * 0.25, 0.7 + 0.3 * i / 11, 0.22)
elif sec == "Outro":
if b < 28:
for k in range(4):
hit(k, 1.0 if b < 24 else 0.9)
elif b < 31:
hit(0)
hit(2)
else:
hit(0, 0.9, 3.5)
return n
def gen_snare_clap(rng):
sn, cl = [], []
for bar in range(TOTAL_BARS):
sec, b, _ = section_at(bar)
t0 = bar * 4.0
back = False
fill = None
if sec == "Build 1" and b >= 16:
back = b < 30
if b == 30:
roll(sn, 38, t0, 4.0, 2, 4, 0.55, 0.95)
if b == 31:
roll(sn, 38, t0, 4.0, 4, 8, 0.7, 1.0)
elif sec == "Drop 1":
back = True
if b % 8 == 7:
fill = "short"
elif sec == "Build 2" and b >= 8:
if b < 28:
back = True
elif b == 28 or b == 29:
roll(sn, 38, t0, 4.0, 2, 3, 0.6, 0.9)
elif b == 30:
roll(sn, 38, t0, 4.0, 4, 6, 0.65, 1.0)
else:
roll(sn, 38, t0, 3.0, 6, 12, 0.7, 1.0, 0.5)
elif sec == "Drop 2":
back = True
if b % 16 == 15:
fill = "long"
elif b % 8 == 7:
fill = "short"
elif sec == "Outro" and b < 16:
back = True
if not back:
continue
vel_scale = 0.8 if sec in ("Build 1", "Build 2", "Outro") else 1.0
for beat in (1, 3):
if beat == 3 and fill:
continue
sn.append((t0 + beat, 0.35, 38, 0.95 * vel_scale))
cl.append((t0 + beat, 0.3, 39, 0.9 * vel_scale))
if fill == "short":
roll(sn, 38, t0 + 3.0, 1.0, 4, 4, 0.6, 1.0)
cl.append((t0 + 3.0, 0.3, 39, 0.9))
elif fill == "long":
roll(sn, 38, t0 + 2.0, 2.0, 4, 8, 0.6, 1.0, 0.5)
if sec in ("Drop 1", "Drop 2") and not fill:
v = (b // 4) % 4
ghosts = {0: [], 1: [(11, .45)], 2: [(7, .4), (15, .5)], 3: [(10, .4), (14, .5)]}[v]
for s, vel in ghosts:
sn.append((t0 + s * 0.25, 0.2, 38, vel))
return sn, cl
def gen_hats(rng):
n = []
def bar_hats(t0, vs, open_off=True, closed=True, roll_end=False, eighths=False):
for s in range(16):
t = t0 + s * 0.25
if eighths and s % 2:
continue
if open_off and s % 4 == 2:
n.append((t + jitter(rng, 0.003), 0.22, 46, 0.85 * vs))
elif closed:
base = 0.72 if s % 4 == 0 else 0.42 + rng.random() * 0.14
n.append((t + (jitter(rng) if s else 0), 0.18, 42, base * vs))
if roll_end:
for s in (13, 15):
n.append((t0 + s * 0.25 + 0.125, 0.1, 42, 0.5 * vs))
for bar in range(TOTAL_BARS):
sec, b, _ = section_at(bar)
t0 = bar * 4.0
if sec == "Intro":
if 4 <= b < 16:
bar_hats(t0, 0.7, closed=False)
elif b >= 16:
bar_hats(t0, 0.5 + 0.4 * (b - 16) / 15)
elif sec == "Build 1":
bar_hats(t0, 0.9, roll_end=(b % 8 == 7))
elif sec in ("Drop 1", "Drop 2"):
bar_hats(t0, 1.0, roll_end=(b % 4 == 3))
elif sec == "Breakdown":
if b >= 16:
bar_hats(t0, 0.35, open_off=False, eighths=True)
elif sec == "Build 2":
if 8 <= b < 16:
bar_hats(t0, 0.7, closed=False)
elif b >= 16:
bar_hats(t0, 0.5 + 0.5 * (b - 16) / 15, roll_end=(b == 31))
elif sec == "Outro":
if b < 16:
bar_hats(t0, 0.85)
elif b < 24:
bar_hats(t0, 0.7, closed=False)
elif b < 28:
bar_hats(t0, 0.3, open_off=False, eighths=True)
return n
PERC_A = [(3, 64, .8), (6, 63, .7), (10, 64, .8), (13, 63, .7), (7, 37, .6), (15, 61, .5)]
PERC_B = [(2, 45, .8), (5, 41, .85), (8, 63, .6), (11, 45, .75), (14, 48, .7), (15, 48, .55)]
PERC_C = [(1, 60, .6), (4, 64, .75), (7, 63, .65), (9, 60, .55), (11, 64, .8), (12, 41, .7), (14, 63, .7)]
def gen_perc(rng):
n = []
def pat(t0, p, vs):
for s, key, vel in p:
n.append((t0 + s * 0.25 + jitter(rng), 0.2, key, min(1.0, vel * vs)))
def shaker(t0, vs):
for s in range(16):
n.append((t0 + s * 0.25 + jitter(rng, 0.003), 0.12, 70, (0.5 if s % 2 else 0.32) * vs))
def tom_fill(t0, vs):
for i, key in enumerate((48, 48, 45, 45, 41, 41, 43, 41)):
n.append((t0 + 2.0 + i * 0.25, 0.2, key, (0.6 + 0.05 * i) * vs))
for bar in range(TOTAL_BARS):
sec, b, _ = section_at(bar)
t0 = bar * 4.0
fill = False
if sec == "Intro":
if b >= 16:
shaker(t0, 0.6)
if b >= 24:
pat(t0, PERC_A, 0.6)
elif sec == "Build 1":
shaker(t0, 0.8)
pat(t0, PERC_A, 0.85)
fill = b % 8 == 7
elif sec == "Drop 1":
shaker(t0, 1.0)
pat(t0, PERC_A if (b // 4) % 2 == 0 else PERC_B, 1.0)
if b >= 32:
pat(t0, PERC_C, 0.8)
fill = b % 8 == 7
elif sec == "Breakdown":
if b >= 20:
shaker(t0, 0.45)
elif sec == "Build 2":
if b >= 8:
shaker(t0, 0.7)
pat(t0, PERC_A, 0.8)
if b >= 16:
pat(t0, PERC_B, 0.8)
fill = b >= 16 and b % 4 == 3
elif sec == "Drop 2":
shaker(t0, 1.0)
v = (b // 4) % 4
for p in ([PERC_A], [PERC_B], [PERC_C], [PERC_A, PERC_B])[v]:
pat(t0, p, 1.0)
fill = b % 8 == 7
elif sec == "Outro":
if b < 16:
shaker(t0, 0.7)
pat(t0, PERC_A, 0.7)
if b < 8:
pat(t0, PERC_B, 0.6)
if fill:
tom_fill(t0, 1.0)
return n
def gen_bass(rng):
n = []
def roll_bar(t0, root, vs, octave_jump, fill, drive=False):
for beat in range(4):
if fill and beat == 3:
for i, semi in enumerate((0, 3, 7, 12)):
n.append((t0 + 3 + i * 0.25, 0.22, root + 12 + semi, 0.95 * vs))
continue
steps = (2, 3) if drive else (1, 2, 3)
for s in steps:
key = root
vel = {1: 0.78, 2: 1.0, 3: 0.85}[s]
if octave_jump and s == 3 and beat in (1, 3):
key += 12
n.append((t0 + beat + s * 0.25, 0.22, key, vel * vs))
def off_bar(t0, root, vs):
for beat in range(4):
n.append((t0 + beat + 0.5, 0.42, root, 0.95 * vs))
for bar in range(TOTAL_BARS):
sec, b, _ = section_at(bar)
t0 = bar * 4.0
root = BASS_ROOT[prog(sec, b)]
start = len(n)
if sec == "Build 1":
if 16 <= b < 24:
off_bar(t0, BASS_ROOT[0], 0.8)
elif b >= 24:
roll_bar(t0, BASS_ROOT[0], 0.55 + 0.4 * (b - 24) / 7, False, False)
elif sec == "Drop 1":
roll_bar(t0, root, 1.0, b % 2 == 1, b % 8 == 7)
elif sec == "Breakdown":
if b >= 8:
n.append((t0, 3.95, root, 0.75))
elif sec == "Build 2":
if 12 <= b < 20:
off_bar(t0, BASS_ROOT[0], 0.8)
elif b >= 20:
roll_bar(t0, root, 0.75 + 0.25 * (b - 20) / 11, b % 2 == 1, False)
elif sec == "Drop 2":
roll_bar(t0, root, 1.0, b % 2 == 1 or b % 4 == 3, b % 8 == 7, drive=(b % 16 >= 12 and b % 8 != 7))
elif sec == "Outro":
if b < 16:
roll_bar(t0, root, 0.9, False, False)
elif b < 24:
off_bar(t0, BASS_ROOT[0], 0.7)
# silence the last beat before the big drops
if (sec in ("Build 1", "Build 2")) and b == 31:
n[start:] = [x for x in n[start:] if x[0] < t0 + 3.0]
return n
def runs(chord_for_bar, bars):
"""Merge consecutive equal chords -> [(first_bar, nbars, chord)]."""
out = []
for bar in bars:
c = chord_for_bar(bar)
if out and out[-1][2] == c and (bar - out[-1][0]) % 8 != 0:
out[-1][1] += 1
else:
out.append([bar, 1, c])
return out
def gen_pad(rng):
n = []
pad_bars = []
for bar in range(TOTAL_BARS):
sec, b, _ = section_at(bar)
if sec == "Breakdown" or (sec == "Build 2") or (sec == "Drop 2"):
pad_bars.append(bar)
for first, nb, c in runs(lambda bar: prog(*section_at(bar)[:2]) if section_at(bar)[0] != "Build 2"
else (section_at(bar)[1] // 4) % 4, pad_bars):
sec, b, _ = section_at(first)
vel = {"Breakdown": 0.6, "Build 2": 0.45, "Drop 2": 0.4}[sec]
for key in CHORDS[c]:
n.append((first * 4.0, nb * 4.0 - 0.05, key, vel))
return n
def gen_lead(rng):
n = []
motif = [ # (beat, chord-tone index, octave, dur) per bar of a 4-bar chord block
[(0, 3, 12, 3.0), (3, 2, 12, 1.0)],
[(0, 0, 24, 4.0)],
[(0, 2, 12, 2.0), (2, 1, 12, 2.0)],
[(0, 0, 12, 4.0)],
]
for bar in range(TOTAL_BARS):
sec, b, _ = section_at(bar)
t0 = bar * 4.0
if sec == "Breakdown" and b >= 8:
c = CHORDS[(b // 4) % 4]
for beat, idx, octv, dur in motif[b % 4]:
n.append((t0 + beat, dur - 0.05, c[idx] + octv, 0.8))
elif (sec == "Build 2" and b >= 16) or (sec == "Drop 2" and b >= 8):
ci = ((b // 4) % 4) if sec == "Build 2" else prog(sec, b)
c = CHORDS[ci]
sixteenths = sec == "Drop 2" and b % 8 >= 4
steps = 16 if sixteenths else 8
gap = 4.0 / steps
order = [0, 1, 2, 3, 2, 1, 2, 3] if steps == 8 else [0, 2, 1, 3] * 4
ramp = 0.5 + 0.4 * (b - 16) / 15 if sec == "Build 2" else 0.85
for i in range(steps):
accent = 1.0 if (i % 2 == 1 if steps == 8 else i % 4 == 2) else 0.7
n.append((t0 + i * gap, gap * 0.8, c[order[i]] + 12, accent * ramp))
return n
def gen_fx(rng):
n = []
# risers (one long note per 8-bar chunk, key rises with the build)
for bar, key in ((56, 60), (152, 62), (176, 64), (184, 67)):
n.append((bar * 4.0, 31.5, key, 0.9))
# impacts (36), crashes (49), reverse crashes (37) at the bar before a drop
for bar in (64, 128, 192):
n.append((bar * 4.0, 3.9, 36, 1.0))
for bar in (32, 160):
n.append((bar * 4.0, 3.9, 36, 0.8))
for sec, start, _ in SECTIONS:
n.append((start * 4.0, 3.9, 49, 0.9))
for bar in (63, 127, 191, 287):
n.append((bar * 4.0, 3.9, 37, 0.9))
return sorted(n)
# name, generator, channel, colour, volume, pan, device hint, drum?
def build_tracks():
r = lambda s: random.Random(1337 + s)
sn, cl = gen_snare_clap(r(2))
return [
("Kick 808", gen_kick(r(1)), 9, "#e63946", 0.90, 0.50, ("Drum Machine", "instrument")),
("Snare", sn, 9, "#f4a261", 0.72, 0.50, ("Drum Machine", "instrument")),
("Clap", cl, 9, "#ffb703", 0.60, 0.52, ("Drum Machine", "instrument")),
("Hats", gen_hats(r(3)), 9, "#e9c46a", 0.55, 0.58, ("Drum Machine", "instrument")),
("Jungle Perc", gen_perc(r(4)), 9, "#2a9d8f", 0.60, 0.40, ("Drum Machine", "instrument")),
("Saw Bass", gen_bass(r(5)), 0, "#8338ec", 0.82, 0.50, ("Polysynth", "instrument")),
("Pad", gen_pad(r(6)), 0, "#3a86ff", 0.50, 0.50, ("Polysynth", "instrument")),
("Lead", gen_lead(r(7)), 0, "#ff006e", 0.50, 0.50, ("Polysynth", "instrument")),
("FX", gen_fx(r(8)), 9, "#adb5bd", 0.55, 0.50, ("Sampler", "instrument")),
]
# ---------------------------------------------------------------- finalise notes
def finalize(notes, limit_beats=TOTAL_BARS * 4.0):
"""Clamp to the arrangement, drop dead notes, clamp velocity, sort."""
out = []
for t, d, key, vel in notes:
t = max(0.0, t)
d = min(d, limit_beats - t)
if d <= 0.01 or vel <= 0:
continue
out.append((round(t, 5), round(d, 5), int(key), round(min(1.0, max(0.05, vel)), 3)))
out.sort(key=lambda x: (x[0], x[2]))
return out
# ---------------------------------------------------------------- MIDI writer
def vlq(v):
b = [v & 0x7F]
v >>= 7
while v:
b.append((v & 0x7F) | 0x80)
v >>= 7
return bytes(reversed(b))
def meta(delta, typ, data):
return vlq(delta) + b"\xFF" + bytes([typ]) + vlq(len(data)) + data
def track_chunk(events):
body = b"".join(events)
return b"MTrk" + struct.pack(">I", len(body)) + body
def note_events(name, channel, notes):
raw = []
for t, d, key, vel in notes:
on = round(t * PPQ)
off = max(on + 1, round((t + d) * PPQ))
raw.append((on, 1, bytes([0x90 | channel, key, max(1, int(vel * 127))])))
raw.append((off, 0, bytes([0x80 | channel, key, 0])))
raw.sort(key=lambda x: (x[0], x[1]))
out = [meta(0, 0x03, name.encode())]
last = 0
for tick, _, data in raw:
out.append(vlq(tick - last) + data)
last = tick
out.append(meta(0, 0x2F, b""))
return out
def conductor():
return [
meta(0, 0x03, TITLE.encode()),
meta(0, 0x51, struct.pack(">I", int(60_000_000 / BPM))[1:]),
meta(0, 0x58, bytes([4, 2, 24, 8])),
meta(0, 0x2F, b""),
]
def write_midi(path, tracks):
chunks = [track_chunk(conductor())]
for name, channel, notes in tracks:
chunks.append(track_chunk(note_events(name, channel, notes)))
header = b"MThd" + struct.pack(">IHHH", 6, 1, len(chunks), PPQ)
with open(path, "wb") as f:
f.write(header + b"".join(chunks))
# ---------------------------------------------------------------- automation
# Filter: a low-pass band on a standard DAWproject Equalizer, cutoff automated in Hz.
# Sidechain: DAWproject has no sidechain routing, so the kick "pump" is written as
# volume-ducking automation on the channel faders (synchronised to the kick notes).
FILTERS = { # track -> (Q, filter order)
"Saw Bass": (1.6, 4),
"Pad": (0.8, 2),
"Lead": (1.4, 2),
}
DUCK = { # track -> (depth = fraction of fader level at the kick hit, release in beats)
"Saw Bass": (0.45, 0.5),
"Pad": (0.25, 0.8),
"Lead": (0.45, 0.5),
}
def hold(pts, bar0, bar1, hz):
pts += [(bar0 * 4.0, hz), (bar1 * 4.0, hz)]
def sweep(pts, bar0, bar1, f0, f1):
"""Exponential (log-frequency) cutoff sweep, one breakpoint per bar."""
n = max(1, bar1 - bar0)
for i in range(n + 1):
pts.append(((bar0 + i) * 4.0, f0 * (f1 / f0) ** (i / n)))
def tidy(pts):
"""Make breakpoint times strictly increasing (a reset becomes a 1/16-beat snap)."""
pts = sorted(pts, key=lambda p: p[0])
for i in range(len(pts) - 2, -1, -1):
if pts[i][0] >= pts[i + 1][0]:
pts[i] = (pts[i + 1][0] - 0.0625, pts[i][1])
return pts
def filter_curves():
"""Cutoff breakpoints in Hz, as {track: [(beat, hz)]}; bars are 0-based."""
bass = []
hold(bass, 0, 48, 150)
sweep(bass, 48, 56, 180, 450) # Build 1: offbeat bass creeps in
sweep(bass, 56, 64, 450, 3200) # Build 1: rolling bass opens up
for i in range(8): # Drop 1: one sweep per 8-bar phrase, ever brighter
sweep(bass, 64 + 8 * i, 72 + 8 * i, 500 + 50 * i, 1500 + 150 * i)
hold(bass, 128, 136, 250) # Breakdown: dark drone ...
sweep(bass, 136, 160, 250, 1200) # ... slowly opening
hold(bass, 160, 172, 600)
sweep(bass, 172, 180, 350, 800) # Build 2: offbeat bass
sweep(bass, 180, 192, 800, 4200) # Build 2: rolling bass opens
for i in range(12): # Drop 2: sweeps get wider every phrase
sweep(bass, 192 + 8 * i, 200 + 8 * i, 900 + 60 * i, min(2200 + 250 * i, 5000))
sweep(bass, 288, 304, 3500, 1500) # Outro: closing down
sweep(bass, 304, 312, 1500, 400)
hold(bass, 312, 320, 400)
pad = []
hold(pad, 0, 128, 400)
sweep(pad, 128, 160, 400, 4500) # Breakdown: pad blooms
hold(pad, 160, 176, 1500)
sweep(pad, 176, 192, 1500, 6000) # Build 2: pad opens into the drop
for i in range(6): # Drop 2: breathing over 16 bars
sweep(pad, 192 + 16 * i, 200 + 16 * i, 2500, 4500)
sweep(pad, 200 + 16 * i, 208 + 16 * i, 4500, 2500)
hold(pad, 288, 320, 2500)
lead = []
hold(lead, 0, 128, 1200)
sweep(lead, 128, 160, 1200, 3500) # Breakdown: melody brightens
hold(lead, 160, 176, 900)
sweep(lead, 176, 192, 900, 7000) # Build 2: arp sweeps wide open
hold(lead, 192, 200, 7000)
for i in range(11): # Drop 2: alternate closing and opening
if i % 2 == 0:
sweep(lead, 200 + 8 * i, 208 + 8 * i, 7000, 3000)
else:
sweep(lead, 200 + 8 * i, 208 + 8 * i, 3000, 7000)
hold(lead, 288, 320, 3500)
return {"Saw Bass": tidy(bass), "Pad": tidy(pad), "Lead": tidy(lead)}
def duck_points(kick_notes, base, depth, release):
"""Fader automation: drop to base*depth on every kick, recover over `release` beats."""
ons = sorted({n[0] for n in kick_notes})
pts = []
ducked = False
if not ons or ons[0] > 0:
pts.append((0.0, base, "hold"))
for i, t in enumerate(ons):
if not ducked:
pts.append((t, base * depth, "linear"))
ducked = True
nxt = ons[i + 1] if i + 1 < len(ons) else None
if nxt is not None and nxt - t <= release + 0.05:
continue # next kick arrives before recovery: stay ducked (kick roll)
pts.append((t + release, base, "hold"))
ducked = False
return pts
# ---------------------------------------------------------------- DAWproject writer
def fmt(x):
return ("%.5f" % x).rstrip("0").rstrip(".")
def chunk_clips(notes):
"""Split notes into 8-bar clips -> [(start_beat, name, [relative notes])]."""
size = CHUNK * 4.0
buckets = {}
for t, d, key, vel in notes:
c = int(t // size)
end = (c + 1) * size
buckets.setdefault(c, []).append((t - c * size, min(d, end - t), key, vel))
out = []
for c in sorted(buckets):
bar = c * CHUNK
sec, b, _ = section_at(bar)
out.append((c * size, "%s %d" % (sec, b // CHUNK + 1), buckets[c]))
return out
def build_dawproject(path, tracks, devices, automation=True, vocal=True):
q = quoteattr
vocal = vocal and os.path.exists(VOCAL_FILE)
if vocal:
with wave.open(VOCAL_FILE) as w:
v_sr, v_ch, v_secs = w.getframerate(), w.getnchannels(), w.getnframes() / w.getframerate()
kick = next(t[1] for t in tracks if t[0] == "Kick 808")
curves = filter_curves() if automation else {}
n_points = 0
x = ['<?xml version="1.0" encoding="UTF-8"?>',
'<Project version="1.0">',
' <Application name="build_track.py" version="1.0"/>',
' <Transport>',
' <Tempo unit="bpm" value="%d" id="tempo"/>' % BPM,
' <TimeSignature numerator="4" denominator="4" id="timesig"/>',
' </Transport>',
' <Structure>']
for i, (name, notes, ch, color, vol, pan, dev) in enumerate(tracks):
x.append(' <Track contentType="notes" loaded="true" id="t%d" name=%s color=%s>' % (i, q(name), q(color)))
x.append(' <Channel role="regular" audioChannels="2" destination="c_master" id="c%d">' % i)
has_filter = automation and name in FILTERS
if devices or has_filter:
x.append(' <Devices>')
if devices:
x.append(' <BuiltinDevice deviceName=%s deviceRole=%s id="d%d"/>' % (q(dev[0]), q(dev[1]), i))
if has_filter:
fq, order = FILTERS[name]
x.append(' <Equalizer deviceName="Filter" deviceRole="audioFX" id="eq%d">' % i)
x.append(' <Band type="lowPass" order="%d">' % order)
x.append(' <Freq unit="hertz" value="%s" min="20" max="20000" id="flt%d"/>'
% (fmt(curves[name][0][1]), i))
x.append(' <Q unit="linear" value="%s" min="0.1" max="10" id="flq%d"/>' % (fmt(fq), i))
x.append(' <Enabled value="true" id="fle%d"/>' % i)
x.append(' </Band>')
x.append(' </Equalizer>')
x.append(' </Devices>')
x.append(' <Pan unit="normalized" value="%s" id="pan%d"/>' % (fmt(pan), i))
x.append(' <Volume unit="linear" value="%s" id="vol%d"/>' % (fmt(vol), i))
x.append(' </Channel>')
x.append(' </Track>')
if vocal:
x.append(' <Track contentType="audio" loaded="true" id="t_vocal" name="Vocal" color=%s>' % q(VOCAL_COLOR))
x.append(' <Channel role="regular" audioChannels="%d" destination="c_master" id="c_vocal">' % v_ch)
x.append(' <Pan unit="normalized" value="0.5" id="pan_vocal"/>')
x.append(' <Volume unit="linear" value="%s" id="vol_vocal"/>' % fmt(VOCAL_VOLUME))
x.append(' </Channel>')
x.append(' </Track>')
x.append(' <Track contentType="audio notes" loaded="true" id="t_master" name="Master">')
x.append(' <Channel role="master" audioChannels="2" id="c_master">')
x.append(' <Volume unit="linear" value="0.8" id="vol_master"/>')
x.append(' </Channel>')
x.append(' </Track>')
x.append(' </Structure>')
x.append(' <Arrangement id="arr">')
x.append(' <Lanes timeUnit="beats" id="lanes_root">')
for i, (name, notes, ch, color, vol, pan, dev) in enumerate(tracks):
x.append(' <Lanes track="t%d" id="lanes%d">' % (i, i))
x.append(' <Clips id="clips%d">' % i)
for start, cname, cn in chunk_clips(notes):
x.append(' <Clip time="%s" duration="%s" contentTimeUnit="beats" name=%s color=%s>'
% (fmt(start), fmt(CHUNK * 4.0), q(cname), q(color)))
x.append(' <Notes>')
for t, d, key, vel in cn:
x.append(' <Note time="%s" duration="%s" channel="0" key="%d" vel="%s" rel="0.5"/>'
% (fmt(t), fmt(d), key, fmt(vel)))
x.append(' </Notes>')
x.append(' </Clip>')
x.append(' </Clips>')
if automation and name in FILTERS:
x.append(' <Points id="auto_flt%d" unit="hertz" timeUnit="beats">' % i)
x.append(' <Target parameter="flt%d"/>' % i)
for t, hz in curves[name]:
x.append(' <RealPoint time="%s" value="%s" interpolation="linear"/>' % (fmt(t), fmt(hz)))
x.append(' </Points>')
n_points += len(curves[name])
if automation and name in DUCK:
depth, rel = DUCK[name]
dp = duck_points(kick, vol, depth, rel)
x.append(' <Points id="auto_duck%d" unit="linear" timeUnit="beats">' % i)
x.append(' <Target parameter="vol%d"/>' % i)
for t, v, interp in dp:
x.append(' <RealPoint time="%s" value="%s" interpolation="%s"/>' % (fmt(t), fmt(v), interp))
x.append(' </Points>')
n_points += len(dp)
x.append(' </Lanes>')
if vocal:
x.append(' <Lanes track="t_vocal" id="lanes_vocal">')
x.append(' <Clips id="clips_vocal">')
for k, bar in enumerate(VOCAL_BARS):
x.append(' <Clip time="%s" duration="%s" contentTimeUnit="seconds" playStart="0" name=%s color=%s>'
% (fmt(bar * 4.0), fmt(v_secs * BPM / 60.0), q("When you change... %d" % (k + 1)), q(VOCAL_COLOR)))
x.append(' <Audio timeUnit="seconds" duration="%s" channels="%d" sampleRate="%d" id="vocal_audio%d">'
% (fmt(v_secs), v_ch, v_sr, k))
x.append(' <File path="audio/%s" external="false"/>' % os.path.basename(VOCAL_FILE))
x.append(' </Audio>')
x.append(' </Clip>')
x.append(' </Clips>')
x.append(' </Lanes>')
x.append(' </Lanes>')
x.append(' <Markers id="markers">')
for name, start, _ in SECTIONS:
x.append(' <Marker time="%s" name=%s/>' % (fmt(start * 4.0), q(name)))
x.append(' </Markers>')
x.append(' </Arrangement>')
x.append('</Project>')
meta_xml = ('<?xml version="1.0" encoding="UTF-8"?>\n<MetaData>\n <Title>%s</Title>\n'
' <Genre>Schranz / Industrial Techno</Genre>\n'
' <Comment>%d BPM, F minor, %d bars. Generated by build_track.py</Comment>\n</MetaData>\n'
% (TITLE, BPM, TOTAL_BARS))
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
z.writestr("metadata.xml", meta_xml)
z.writestr("project.xml", "\n".join(x) + "\n")
if vocal:
z.write(VOCAL_FILE, "audio/" + os.path.basename(VOCAL_FILE))
return n_points
def main():
devices = "--devices" in sys.argv
tracks = [(n, finalize(notes), ch, col, vol, pan, dev) for n, notes, ch, col, vol, pan, dev in build_tracks()]
os.makedirs(os.path.join(HERE, "midi"), exist_ok=True)
write_midi(os.path.join(HERE, "midi", "full_arrangement.mid"), [(t[0], t[2], t[1]) for t in tracks])
for i, (name, notes, ch, *_rest) in enumerate(tracks, 1):
slug = name.lower().replace(" ", "_")
write_midi(os.path.join(HERE, "midi", "%02d_%s.mid" % (i, slug)), [(name, ch, notes)])
out = os.path.join(HERE, "exit-progressive-emulation.dawproject")
n_auto = build_dawproject(out, tracks, devices, automation="--no-automation" not in sys.argv,
vocal="--no-vocal" not in sys.argv)
secs = TOTAL_BARS * 4 * 60 / BPM
print("%s: %d bars @ %d BPM = %d:%02d" % (TITLE, TOTAL_BARS, BPM, secs // 60, secs % 60))
for name, notes, *_ in tracks:
print(" %-12s %5d notes" % (name, len(notes)))
print("automation breakpoints: %d" % n_auto)
print("vocal track: %s" % ("yes (bars %s)" % ", ".join(str(b + 1) for b in VOCAL_BARS)
if "--no-vocal" not in sys.argv and os.path.exists(VOCAL_FILE) else "no"))
print("wrote", out)
if __name__ == "__main__":
main()