The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Afterhours · Music Studio</title><link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3EMusic%20Studio%20%E2%80%94%20five%20tracks%20after%20dark%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%23272537%22%2F%3E%0A%20%20%3Cpath%20d%3D%22M67%2017a15%2015%200%201%200%2012%2024%2016%2016%200%200%201-12-24Z%22%20fill%3D%22%23edbfa9%22%2F%3E%0A%20%20%3Cg%20fill%3D%22%23d6c7e9%22%3E%0A%20%20%20%20%3Crect%20x%3D%2219%22%20y%3D%2247%22%20width%3D%228%22%20height%3D%2221%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2232%22%20y%3D%2231%22%20width%3D%228%22%20height%3D%2245%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2245%22%20y%3D%2242%22%20width%3D%228%22%20height%3D%2226%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2258%22%20y%3D%2253%22%20width%3D%228%22%20height%3D%2223%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2271%22%20y%3D%2253%22%20width%3D%228%22%20height%3D%2215%22%20rx%3D%224%22%2F%3E%0A%20%20%3C%2Fg%3E%0A%3C%2Fsvg%3E%0A"><style>:root{color-scheme:dark;--bg:#10121a;--panel:#191d29;--line:#ffffff16;--ink:#f3ede8;--muted:#9299aa;--accent:#eabe90;--purple:#b9acf1;font:13px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink)}button,input,select{font:inherit;color:inherit;background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:8px 11px;min-width:0}button{cursor:pointer;touch-action:manipulation}button:hover{border-color:#8d819f}button:focus-visible,input:focus-visible,canvas:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px}button:disabled{opacity:.4;cursor:default}button.primary,.play{background:var(--accent);color:#1a1820;border:0;font-weight:650}button[aria-pressed=true]{border-color:var(--accent);color:var(--accent);background:#47352c}input[type=range]{padding:0;width:100%;accent-color:var(--accent)}input[type=number]{font-variant-numeric:tabular-nums}h1,h2,p{margin:0}h1{font-size:38px;font-weight:550;line-height:1.05;letter-spacing:-.045em;margin:9px 0 12px}h2{font-size:14px;font-weight:550}.eyebrow{font:9px/1.5 ui-monospace,monospace;letter-spacing:.18em;color:var(--muted)}header{display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:72px;padding:16px 26px;border-bottom:1px solid var(--line)}.identity{display:flex;align-items:center;gap:11px;font-size:11px;letter-spacing:.08em;font-weight:650}.identity>span:last-child{border-left:1px solid var(--line);padding-left:12px;font-size:9px;color:var(--muted);font-weight:400}.brand-icon,.brand-icon svg{width:28px;height:28px;display:block}.file-actions,.small-actions,.exports,.transport-buttons{display:flex;align-items:center;gap:8px}main{display:grid;grid-template-columns:minmax(0,1fr) 248px;max-width:1900px;margin:auto}.main-panel{padding:30px;min-width:0}aside{padding:28px 22px;border-left:1px solid var(--line)}.project-heading{display:flex;align-items:center;justify-content:space-between;gap:32px}#brief{max-width:610px;font-size:12px;color:#aeb4c4;line-height:1.7}.project-controls{display:flex;align-items:end;gap:12px;flex-shrink:0}.project-controls label{width:67px}.project-controls input{width:100%}.project-controls #meter{font-size:11px;color:var(--muted);padding-bottom:25px}label{display:flex;flex-direction:column;gap:7px;font-size:11px;color:#c4c8d2;margin:15px 0}label output{font-size:10px;color:var(--muted)}.transport{display:flex;align-items:center;justify-content:space-between;margin:26px 0 16px;gap:14px}#time{font:11px ui-monospace,monospace;color:var(--muted);margin-left:10px;white-space:nowrap}.wave-stage{background:linear-gradient(120deg,#201e30,#191d2b);border:1px solid var(--line);border-radius:8px;overflow:hidden}.wave-stage canvas{width:100%;height:110px;display:block;cursor:pointer}.mix-stats{display:flex;justify-content:space-between;gap:10px;border-top:1px solid var(--line);padding:10px 15px;color:var(--muted);font:9px ui-monospace,monospace}.section-heading{display:flex;justify-content:space-between;align-items:center;gap:14px;margin:25px 0 13px}.small-actions button{font-size:10px;padding:6px 10px}.hint{color:var(--muted);font-size:10px;line-height:1.65;margin-top:5px}.sections{margin-left:156px;height:28px;position:relative;overflow:hidden}.section{position:absolute;top:0;height:24px;border-left:1px solid #b9acf166;color:#b9acf1;font:9px ui-monospace,monospace;white-space:nowrap;padding:4px 6px;background:#b9acf10a;overflow:hidden}.tracks{border:1px solid var(--line);border-radius:7px;overflow:hidden}.track{display:grid;grid-template-columns:155px minmax(0,1fr);border-bottom:1px solid var(--line);height:49px}.track:last-child{border-bottom:0}.track.selected{background:#b9acf110}.track-info{display:flex;align-items:center;gap:4px;padding:0 8px;border-right:1px solid var(--line);min-width:0}.track-info .track-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;text-align:left;border:0;background:transparent;padding:6px 2px;font-size:11px}.track-info .mini{font-size:8px;padding:3px 5px}.track canvas{width:100%;height:48px;display:block;cursor:pointer}.piano-stage{border:1px solid var(--line);border-radius:7px;overflow:hidden;background:#131722}#piano{height:250px;width:100%;display:block;touch-action:none;cursor:crosshair}.note-editor{display:grid;grid-template-columns:90px 90px 85px minmax(90px,1fr) auto;gap:12px;align-items:end}.note-editor button{margin-bottom:15px;font-size:10px}.note-editor input:not([type=range]){width:100%}.note-editor label{margin:12px 0 15px;font-size:10px}.edit-actions{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-top:3px;padding:13px 0;border-bottom:1px solid var(--line)}.edit-actions button{font-size:10px}.edit-actions span{font-size:9px;color:var(--muted)}.handoff{display:grid;grid-template-columns:1fr 1fr;gap:30px;margin-top:27px}.handoff h2{font-size:19px;letter-spacing:-.025em;margin:5px 0 9px}.handoff p:not(.eyebrow),.handoff details{font-size:11px;line-height:1.7;color:var(--muted)}.handoff summary{color:var(--accent);cursor:pointer}.handoff details p{margin-top:12px}.rule{height:1px;background:var(--line);margin:23px 0}.mixer-buttons,.transpose{display:flex;gap:8px}.mixer-buttons button,.transpose button{flex:1;font-size:11px}.quiet{font-size:10px;width:100%;margin-top:10px;color:var(--muted)}#toast{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);max-width:90vw;border-radius:7px;background:#ede1d5;color:#17141d;padding:11px 18px;opacity:0;pointer-events:none;box-shadow:0 12px 35px #0007;z-index:20;font-size:12px}#toast.visible{opacity:1}.error{position:fixed;bottom:20px;left:20px;right:280px;background:#442628;border:1px solid #ad6160;border-radius:7px;padding:14px;color:#ffe0de;z-index:10}.notice{padding:12px 25px;background:#413623;display:flex;gap:12px;align-items:center;font-size:11px}.notice button{font-size:11px}[hidden]{display:none!important}@media(min-width:1500px){.main-panel{padding:35px 45px}main{grid-template-columns:minmax(0,1fr) 280px}#piano{height:285px}.track{height:57px}.track canvas{height:56px}}@media(max-width:1100px){.identity>span:last-child{display:none}main{grid-template-columns:minmax(0,1fr) 215px}.main-panel{padding:24px 20px}aside{padding:24px 16px}.project-heading{display:block}.project-controls{margin-top:8px}.project-controls label{margin-bottom:0}.project-controls #meter{padding-bottom:10px}.transport{flex-wrap:wrap}.note-editor{grid-template-columns:65px 70px 70px minmax(60px,1fr)}.note-editor button{grid-column:1/-1;margin-top:-10px}.handoff{grid-template-columns:1fr;gap:16px}}@media(max-width:700px){header{padding:14px;flex-wrap:wrap}.file-actions{width:100%}.file-actions button{flex:1;font-size:10px}main{display:block}.main-panel{padding:25px 14px}aside{border-top:1px solid var(--line);border-left:0;padding:24px;display:grid;grid-template-columns:1fr 1fr;gap:0 20px}aside>.eyebrow,aside>.rule,aside>.hint{grid-column:1/-1}.track{grid-template-columns:110px minmax(0,1fr)}.track-info{padding:0 5px}.track-info .track-name{font-size:9px}.track-info .mini{padding:2px 3px}.sections{margin-left:111px}.section-heading{flex-wrap:wrap}.small-actions{gap:5px;flex-wrap:wrap}.small-actions button{font-size:9px}.transport-buttons{gap:6px}#time{margin-left:0;font-size:10px}.transport button,.exports button{font-size:11px}.mix-stats{font-size:8px}.edit-actions{align-items:flex-start;flex-direction:column}.notice{flex-wrap:wrap}.error{right:20px}h1{font-size:34px}.note-editor{grid-template-columns:60px 70px 70px minmax(45px,1fr);gap:9px}.note-editor button{grid-column:auto;margin-top:0;grid-column:1/3}#piano{height:245px}}
.transport{position:sticky;top:0;z-index:5;background:var(--bg);padding:10px 0}aside{position:sticky;top:0;height:100vh;overflow:auto}@media(max-width:700px){aside{position:static;height:auto;overflow:visible}}
</style></head><body>
<header><div class="identity"><span class="brand-icon"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">
<title>Music Studio — five tracks after dark</title>
<rect x="4" y="4" width="88" height="88" rx="23" fill="#272537"/>
<path d="M67 17a15 15 0 1 0 12 24 16 16 0 0 1-12-24Z" fill="#edbfa9"/>
<g fill="#d6c7e9">
<rect x="19" y="47" width="8" height="21" rx="4"/>
<rect x="32" y="31" width="8" height="45" rx="4"/>
<rect x="45" y="42" width="8" height="26" rx="4"/>
<rect x="58" y="53" width="8" height="23" rx="4"/>
<rect x="71" y="53" width="8" height="15" rx="4"/>
</g>
</svg>
</span>AFTERHOURS<span>MUSIC STUDIO</span></div><div class="file-actions"><button id="open-project">Open project</button><button id="save-project">Save project</button><button id="export-stems" class="primary">Stems + project ↗</button></div></header>
<div class="notice" id="revision-notice" hidden><span>A new agent revision is available. Your saved mix and notes are still here.</span><button id="use-revision">Use new version</button><button id="keep-draft">Keep my draft</button></div>
<main><section class="main-panel"><div class="project-heading"><div><p class="eyebrow">YOUR COMPOSITION</p><h1 id="title"></h1><p id="brief"></p></div><div class="project-controls"><label>Tempo<input id="tempo" type="number" min="30" max="240" step="0.001"></label><label>Bars<input id="bars" type="number" min="1" max="256"></label><span id="meter"></span></div></div>
<div class="transport"><div class="transport-buttons"><button id="play" class="play" aria-label="Play">▶ Play</button><button id="stop">■ Stop</button><span id="time">0:00 / 0:00</span></div><div class="exports"><button id="export-wav">Export WAV ↗</button><button id="export-midi">Export MIDI ↗</button></div></div>
<div class="wave-stage"><canvas id="waveform" aria-label="Rendered stereo waveform"></canvas><div class="mix-stats"><span id="audio-status">Preparing your mix</span><span id="level">48 kHz / stereo</span></div></div>
<div class="section-heading"><h2>Arrangement</h2><div class="small-actions"><button id="open-midi">Open MIDI</button><button id="import-audio">Add recording</button><button id="add-track">+ Instrument</button></div></div>
<div id="sections" class="sections"></div><div id="tracks" class="tracks"></div>
<div class="section-heading"><div><h2 id="piano-title">Notes</h2><p class="hint">Click to add. Drag to move. Select a note to change its pitch, length or touch.</p></div><div class="small-actions"><button id="previous-bars" aria-label="Previous bars">←</button><span id="bar-window"></span><button id="next-bars" aria-label="Next bars">→</button></div></div>
<div class="piano-stage"><canvas id="piano" aria-label="Editable piano roll" tabindex="0"></canvas></div>
<div class="note-editor"><label>Pitch<input id="note-pitch" value="C4" size="5"></label><label>Start beat<input id="note-start" type="number" min="0" step="0.25"></label><label>Length<input id="note-length" type="number" min="0.125" step="0.25" value="1"></label><label>Touch<input id="note-velocity" type="range" min="0.05" max="1" step="0.01" value="0.75"></label><button id="delete-note">Delete note</button></div>
<div class="edit-actions"><div><button id="undo">↶ Undo</button><button id="redo">↷ Redo</button><button id="duplicate-section">Repeat these bars</button></div><span id="draft-status">Draft saved on this device</span></div>
<div class="handoff"><div><p class="eyebrow">KEEP MAKING IT YOURS</p><h2>A piece you can take anywhere.</h2><p>Bring your own MIDI or recordings. Keep the notes editable. Export the mix and separate tracks to continue in your DAW.</p></div><details><summary>Make a completely different piece</summary><p>Describe it in the Harness chat. Give the purpose, mood, length and any melody or recording you want to use. The agent writes a complete arrangement for your brief. This example is not a genre restriction.</p><p>Try: “Make a 40-second title sequence for a coastal documentary. Start with an intimate plucked motif, open into warm harmony, then end on a quiet resolved chord. Leave room for my voiceover.”</p></details></div>
</section><aside><p class="eyebrow">SELECTED TRACK</p><label>Track name<input id="track-name"></label><label>Sound<select id="instrument"></select></label><div id="sampler-controls" hidden><label>Sample<select id="sample-id"></select></label><label>Original pitch<input id="sample-root" value="C4"></label></div>
<div class="mixer-buttons"><button id="mute">Mute</button><button id="solo">Solo</button></div>
<label>Level <output id="gain-label"></output><input id="gain" type="range" min="0" max="1.5" step="0.01"></label><label>Position <output id="pan-label"></output><input id="pan" type="range" min="-1" max="1" step="0.01"></label>
<div class="rule"></div><p class="eyebrow">SHAPE THE SOUND</p><label>Soft entrance<input id="attack" type="range" min="0.001" max="3" step="0.001"></label><label>Release<input id="release" type="range" min="0.01" max="3" step="0.01"></label><label>Brightness<input id="tone" type="range" min="100" max="20000" step="100"></label><label>Room<input id="space" type="range" min="0" max="0.8" step="0.01"></label><label>Echo<input id="delay" type="range" min="0" max="0.6" step="0.01"></label>
<div id="clip-controls" hidden><div class="rule"></div><p class="eyebrow">RECORDING</p><label>Clip<select id="clip-select"></select></label><label>Start beat<input id="clip-beat" type="number" min="0" step="0.25"></label><label>Trim start (seconds)<input id="clip-offset" type="number" min="0" step="0.01"></label><label>Length (seconds)<input id="clip-duration" type="number" min="0.01" step="0.01"></label></div>
<div class="rule"></div><div class="transpose"><button id="transpose-down">− Octave</button><button id="transpose-up">+ Octave</button></div><button id="remove-track" class="quiet">Remove track</button><div class="rule"></div><p class="eyebrow">MASTER</p><label>Output level<input id="master" type="range" min="0" max="1" step="0.01"></label><p class="hint">WAV: 48 kHz, stereo, 16-bit. Stems follow mute and solo. MIDI keeps all notes; recordings travel as audio.</p><button id="export-html" class="quiet">Portable studio ↗</button><button id="reset-project" class="quiet">Restore agent version</button></aside></main>
<div id="error" class="error" role="alert" hidden></div><div id="toast" role="status"></div><input id="project-file" type="file" accept=".json" hidden><input id="midi-file" type="file" accept=".mid,.midi" hidden><input id="audio-file" type="file" accept="audio/wav,audio/mpeg,audio/mp3,audio/ogg,audio/mp4" hidden>
<script id="afterhours-data" type="application/json">{"spec":"afterhours/1","id":"blue-hour","title":"Blue Hour","brief":"A 48-second title cue for a coastal documentary. An intimate plucked motif opens into warm harmony and a restrained pulse, then resolves quietly. The arrangement leaves space for a voiceover.","seed":"blue-hour","tempo":100,"meter":[4,4],"beats":80,"tail":0,"master":0.9,"sections":[{"name":"First light","beat":0,"length":16},{"name":"Footsteps","beat":16,"length":16},{"name":"Open water","beat":32,"length":16},{"name":"The lift","beat":48,"length":16},{"name":"Home","beat":64,"length":16}],"tracks":[{"id":"motif","name":"Plucked motif","instrument":"pluck","gain":0.92,"pan":-0.22,"tone":7200,"space":0.18,"delay":0.12,"release":0.35,"notes":[{"beat":0,"midi":62,"duration":0.9,"velocity":0.5645551978774368},{"beat":1.5,"midi":69,"duration":0.55,"velocity":0.5156839515805244},{"beat":3,"midi":73,"duration":0.55,"velocity":0.5337221220098436},{"beat":4,"midi":69,"duration":0.9,"velocity":0.5704508999161422},{"beat":5.5,"midi":73,"duration":0.55,"velocity":0.5553384073100984},{"beat":7,"midi":78,"duration":0.55,"velocity":0.5486000507526099},{"beat":8,"midi":59,"duration":0.9,"velocity":0.542434654519707},{"beat":9.5,"midi":66,"duration":0.55,"velocity":0.5555654297582805},{"beat":11,"midi":69,"duration":0.55,"velocity":0.5576091022111475},{"beat":12,"midi":66,"duration":0.9,"velocity":0.5498305642195046},{"beat":13.5,"midi":69,"duration":0.55,"velocity":0.5180191269449889},{"beat":15,"midi":74,"duration":0.55,"velocity":0.551269242669642},{"beat":16,"midi":55,"duration":0.9,"velocity":0.5297916078120469},{"beat":16.75,"midi":62,"duration":0.55,"velocity":0.531561849565804},{"beat":17.5,"midi":66,"duration":0.55,"velocity":0.5246851859532295},{"beat":18,"midi":71,"duration":0.9,"velocity":0.5459769469805061},{"beat":18.75,"midi":55,"duration":0.55,"velocity":0.5430110706716775},{"beat":19.5,"midi":62,"duration":0.55,"velocity":0.5556431808911263},{"beat":20,"midi":62,"duration":0.9,"velocity":0.5426485464416444},{"beat":20.75,"midi":66,"duration":0.55,"velocity":0.551458582278341},{"beat":21.5,"midi":71,"duration":0.55,"velocity":0.5649891081705689},{"beat":22,"midi":55,"duration":0.9,"velocity":0.5389283135816455},{"beat":22.75,"midi":62,"duration":0.55,"velocity":0.5602186762280762},{"beat":23.5,"midi":66,"duration":0.55,"velocity":0.5550721922561526},{"beat":24,"midi":57,"duration":0.9,"velocity":0.5556441643811761},{"beat":24.75,"midi":64,"duration":0.55,"velocity":0.5601637458100914},{"beat":25.5,"midi":69,"duration":0.55,"velocity":0.5181704859040677},{"beat":26,"midi":73,"duration":0.9,"velocity":0.5534745311327278},{"beat":26.75,"midi":57,"duration":0.55,"velocity":0.5393594153784215},{"beat":27.5,"midi":64,"duration":0.55,"velocity":0.580917686356604},{"beat":28,"midi":64,"duration":0.9,"velocity":0.5533817687354982},{"beat":28.75,"midi":69,"duration":0.55,"velocity":0.5587183390788734},{"beat":29.5,"midi":73,"duration":0.55,"velocity":0.5792586211293935},{"beat":30,"midi":57,"duration":0.9,"velocity":0.573284814916551},{"beat":30.75,"midi":64,"duration":0.55,"velocity":0.5703277547985315},{"beat":31.5,"midi":69,"duration":0.55,"velocity":0.5619088765397667},{"beat":32,"midi":62,"duration":0.9,"velocity":0.5153246533192694},{"beat":32.75,"midi":69,"duration":0.55,"velocity":0.5237792561523615},{"beat":33.5,"midi":73,"duration":0.55,"velocity":0.5725928144164383},{"beat":34,"midi":78,"duration":0.9,"velocity":0.5557868683211505},{"beat":34.75,"midi":62,"duration":0.55,"velocity":0.5406799630582332},{"beat":35.5,"midi":69,"duration":0.55,"velocity":0.5282267559967935},{"beat":36,"midi":69,"duration":0.9,"velocity":0.5165786395415664},{"beat":36.75,"midi":73,"duration":0.55,"velocity":0.5615075619526207},{"beat":37.5,"midi":78,"duration":0.55,"velocity":0.5189804663449525},{"beat":38,"midi":62,"duration":0.9,"velocity":0.5445952211908995},{"beat":38.75,"midi":69,"duration":0.55,"velocity":0.5558770329765975},{"beat":39.5,"midi":73,"duration":0.55,"velocity":0.5320751886576414},{"beat":40,"midi":59,"duration":0.9,"velocity":0.5198988145969808},{"beat":40.75,"midi":66,"duration":0.55,"velocity":0.5620267365992069},{"beat":41.5,"midi":69,"duration":0.55,"velocity":0.5809937621548772},{"beat":42,"midi":74,"duration":0.9,"velocity":0.5508571488857269},{"beat":42.75,"midi":59,"duration":0.55,"velocity":0.5699040935456753},{"beat":43.5,"midi":66,"duration":0.55,"velocity":0.578915261233598},{"beat":44,"midi":66,"duration":0.9,"velocity":0.5367697411932051},{"beat":44.75,"midi":69,"duration":0.55,"velocity":0.5672844250261783},{"beat":45.5,"midi":74,"duration":0.55,"velocity":0.5304293285422027},{"beat":46,"midi":59,"duration":0.9,"velocity":0.5438700043462216},{"beat":46.75,"midi":66,"duration":0.55,"velocity":0.5440233726710081},{"beat":47.5,"midi":69,"duration":0.55,"velocity":0.5674215055428445},{"beat":48,"midi":55,"duration":0.9,"velocity":0.672498374399729},{"beat":48.75,"midi":62,"duration":0.55,"velocity":0.7142857280028984},{"beat":49.5,"midi":66,"duration":0.55,"velocity":0.6693470929078758},{"beat":50,"midi":71,"duration":0.9,"velocity":0.6544555243700743},{"beat":50.75,"midi":55,"duration":0.55,"velocity":0.7016154746282844},{"beat":51.5,"midi":62,"duration":0.55,"velocity":0.7146699369736016},{"beat":52,"midi":62,"duration":0.9,"velocity":0.6642920906236396},{"beat":52.75,"midi":66,"duration":0.55,"velocity":0.7161841747676952},{"beat":53.5,"midi":71,"duration":0.55,"velocity":0.6836484735189006},{"beat":54,"midi":55,"duration":0.9,"velocity":0.670372108512558},{"beat":54.75,"midi":62,"duration":0.55,"velocity":0.693134555073455},{"beat":55.5,"midi":66,"duration":0.55,"velocity":0.6526450070301071},{"beat":56,"midi":57,"duration":0.9,"velocity":0.6671485533202067},{"beat":56.75,"midi":64,"duration":0.55,"velocity":0.7067000186173245},{"beat":57.5,"midi":69,"duration":0.55,"velocity":0.6841152801522985},{"beat":58,"midi":73,"duration":0.9,"velocity":0.6866803099540993},{"beat":58.75,"midi":57,"duration":0.55,"velocity":0.6533734201705083},{"beat":59.5,"midi":64,"duration":0.55,"velocity":0.6772519801398739},{"beat":60,"midi":64,"duration":0.9,"velocity":0.6657161834491416},{"beat":60.75,"midi":69,"duration":0.55,"velocity":0.6660698143094779},{"beat":61.5,"midi":73,"duration":0.55,"velocity":0.6567942600864917},{"beat":62,"midi":57,"duration":0.9,"velocity":0.6868582462500781},{"beat":62.75,"midi":64,"duration":0.55,"velocity":0.6881102317394688},{"beat":63.5,"midi":69,"duration":0.55,"velocity":0.6895300984820351},{"beat":64,"midi":62,"duration":0.9,"velocity":0.5748425221830606},{"beat":64.75,"midi":69,"duration":0.55,"velocity":0.5556503183364868},{"beat":65.5,"midi":73,"duration":0.55,"velocity":0.5547063233807682},{"beat":66,"midi":78,"duration":0.9,"velocity":0.5626272984817624},{"beat":66.75,"midi":62,"duration":0.55,"velocity":0.522831639175117},{"beat":67.5,"midi":69,"duration":0.55,"velocity":0.5546279738426209},{"beat":68,"midi":69,"duration":0.9,"velocity":0.5413805456191301},{"beat":68.75,"midi":73,"duration":0.55,"velocity":0.5201513358294964},{"beat":69.5,"midi":78,"duration":0.55,"velocity":0.5385957259826362},{"beat":70,"midi":62,"duration":0.9,"velocity":0.534280517487973},{"beat":70.75,"midi":69,"duration":0.55,"velocity":0.5577538215406239},{"beat":71.5,"midi":73,"duration":0.55,"velocity":0.5772834022156894},{"beat":72,"midi":59,"duration":0.9,"velocity":0.4230030191425234},{"beat":74,"midi":66,"duration":0.55,"velocity":0.38740793404039},{"beat":76,"midi":66,"duration":0.9,"velocity":0.3901720629170537},{"beat":78,"midi":69,"duration":0.55,"velocity":0.40686308683957906},{"beat":77.5,"midi":74,"duration":1.4,"velocity":0.343521455296129}],"muted":false,"solo":false,"attack":0.008,"sampleRoot":60,"clips":[]},{"id":"felt","name":"Felt melody","instrument":"felt","gain":0.7,"pan":0.15,"tone":5200,"space":0.24,"release":0.75,"notes":[{"beat":16,"midi":71,"duration":1.1,"velocity":0.4673883465398103},{"beat":17.5,"midi":69,"duration":0.8,"velocity":0.49379954020492733},{"beat":19,"midi":66,"duration":1.7,"velocity":0.6301682471336797},{"beat":21.5,"midi":62,"duration":1.8,"velocity":0.49152300154324624},{"beat":24,"midi":69,"duration":1.1,"velocity":0.4603718268405646},{"beat":25.5,"midi":73,"duration":0.8,"velocity":0.48717615934088826},{"beat":27,"midi":76,"duration":1.7,"velocity":0.6432531002314761},{"beat":29.5,"midi":73,"duration":1.8,"velocity":0.4998916279897094},{"beat":32,"midi":74,"duration":1.1,"velocity":0.501504489555955},{"beat":33.5,"midi":73,"duration":0.8,"velocity":0.48988275276497006},{"beat":35,"midi":69,"duration":1.7,"velocity":0.5941922905027867},{"beat":37.5,"midi":66,"duration":1.8,"velocity":0.48086906783282757},{"beat":40,"midi":73,"duration":1.1,"velocity":0.5025697763077915},{"beat":41.5,"midi":69,"duration":0.8,"velocity":0.48952602764125913},{"beat":43,"midi":66,"duration":1.7,"velocity":0.5855324333235622},{"beat":45.5,"midi":62,"duration":1.8,"velocity":0.5071403011493385},{"beat":48,"midi":71,"duration":1.1,"velocity":0.46563015357125553},{"beat":49.5,"midi":69,"duration":0.8,"velocity":0.49834976814221593},{"beat":51,"midi":66,"duration":1.7,"velocity":0.5926955807154999},{"beat":53.5,"midi":62,"duration":1.8,"velocity":0.4645159267447889},{"beat":56,"midi":69,"duration":1.1,"velocity":0.4845800973614678},{"beat":57.5,"midi":73,"duration":0.8,"velocity":0.5087262404616922},{"beat":59,"midi":76,"duration":1.7,"velocity":0.641343982924521},{"beat":61.5,"midi":73,"duration":1.8,"velocity":0.48929653075523677},{"beat":64,"midi":74,"duration":1.1,"velocity":0.46052718054037545},{"beat":65.5,"midi":73,"duration":0.8,"velocity":0.4692010128684342},{"beat":67,"midi":69,"duration":1.7,"velocity":0.6186143748374656},{"beat":69.5,"midi":66,"duration":1.8,"velocity":0.5143161941040307},{"beat":76,"midi":62,"duration":2.7,"velocity":0.3558878572102636},{"beat":76.09,"midi":69,"duration":2.6,"velocity":0.35292200230546295},{"beat":76.18,"midi":74,"duration":2.5,"velocity":0.34290987599417566},{"beat":76.27,"midi":78,"duration":2.4000000000000004,"velocity":0.3397677047353238}],"muted":false,"solo":false,"attack":0.008,"delay":0,"sampleRoot":60,"clips":[]},{"id":"pad","name":"Warm horizon","instrument":"pad","gain":0.24,"pan":0,"tone":1600,"attack":0.55,"space":0.35,"release":0.9,"notes":[{"beat":16,"midi":62,"duration":7.5,"velocity":0.37253679525852207},{"beat":16.045,"midi":66,"duration":7.5,"velocity":0.3803293997310102},{"beat":16.09,"midi":71,"duration":7.5,"velocity":0.4021729043647647},{"beat":24,"midi":64,"duration":7.5,"velocity":0.3783894086442888},{"beat":24.045,"midi":69,"duration":7.5,"velocity":0.3832112705297768},{"beat":24.09,"midi":73,"duration":7.5,"velocity":0.40341265460848813},{"beat":32,"midi":69,"duration":7.5,"velocity":0.40125959977880127},{"beat":32.045,"midi":73,"duration":7.5,"velocity":0.3932125707380474},{"beat":32.09,"midi":78,"duration":7.5,"velocity":0.3723255736678839},{"beat":40,"midi":66,"duration":7.5,"velocity":0.38505192853137854},{"beat":40.045,"midi":69,"duration":7.5,"velocity":0.39397476967051626},{"beat":40.09,"midi":74,"duration":7.5,"velocity":0.3787869536057115},{"beat":48,"midi":62,"duration":7.5,"velocity":0.5097104608826339},{"beat":48.045,"midi":66,"duration":7.5,"velocity":0.4887416532775387},{"beat":48.09,"midi":71,"duration":7.5,"velocity":0.4663905056659132},{"beat":56,"midi":64,"duration":7.5,"velocity":0.47987989383284},{"beat":56.045,"midi":69,"duration":7.5,"velocity":0.4905236521502957},{"beat":56.09,"midi":73,"duration":7.5,"velocity":0.5169125688262284},{"beat":64,"midi":69,"duration":7.5,"velocity":0.36891332033276564},{"beat":64.045,"midi":73,"duration":7.5,"velocity":0.38823245551437147},{"beat":64.09,"midi":78,"duration":7.5,"velocity":0.3705159105472267}],"muted":false,"solo":false,"delay":0,"sampleRoot":60,"clips":[]},{"id":"bass","name":"Low tide","instrument":"bass","gain":0.55,"pan":0,"tone":1100,"space":0.02,"release":0.2,"notes":[{"beat":32,"midi":38,"duration":2.7,"velocity":0.5659881625939162},{"beat":36,"midi":38,"duration":2.7,"velocity":0.57739312787354},{"beat":39,"midi":38,"duration":0.75,"velocity":0.4011168014382943},{"beat":40,"midi":35,"duration":2.7,"velocity":0.5901264471597971},{"beat":44,"midi":35,"duration":2.7,"velocity":0.5557340490985663},{"beat":47,"midi":35,"duration":0.75,"velocity":0.38950243089739234},{"beat":48,"midi":31,"duration":2.7,"velocity":0.7510273775272072},{"beat":52,"midi":31,"duration":2.7,"velocity":0.7463892952236347},{"beat":55,"midi":31,"duration":0.75,"velocity":0.4253533074991777},{"beat":56,"midi":33,"duration":2.7,"velocity":0.7061171898711472},{"beat":60,"midi":33,"duration":2.7,"velocity":0.7267716949526222},{"beat":63,"midi":33,"duration":0.75,"velocity":0.40719077550172805},{"beat":64,"midi":38,"duration":2.7,"velocity":0.5554849594887347},{"beat":68,"midi":38,"duration":2.7,"velocity":0.6220494564995172},{"beat":71,"midi":38,"duration":0.75,"velocity":0.39888761456049976}],"muted":false,"solo":false,"attack":0.008,"delay":0,"sampleRoot":60,"clips":[]},{"id":"pulse","name":"Soft pulse","instrument":"drums","gain":0.4,"pan":0.04,"tone":12000,"space":0.06,"release":0.05,"notes":[{"beat":32,"midi":36,"duration":0.15,"velocity":0.6424152635859326},{"beat":34.5,"midi":36,"duration":0.15,"velocity":0.38359787704553455},{"beat":34,"midi":38,"duration":0.12,"velocity":0.267568149670586},{"beat":32.5,"midi":42,"duration":0.08,"velocity":0.26824469596356154},{"beat":33,"midi":42,"duration":0.08,"velocity":0.15431948463171724},{"beat":33.5,"midi":42,"duration":0.08,"velocity":0.2763720994761586},{"beat":34,"midi":42,"duration":0.08,"velocity":0.16475707195252184},{"beat":34.5,"midi":42,"duration":0.08,"velocity":0.28171498903155323},{"beat":35,"midi":42,"duration":0.08,"velocity":0.14896126154810194},{"beat":35.5,"midi":42,"duration":0.08,"velocity":0.28008688166856766},{"beat":36,"midi":36,"duration":0.15,"velocity":0.6103359449379147},{"beat":38.5,"midi":36,"duration":0.15,"velocity":0.34600719700139015},{"beat":38,"midi":38,"duration":0.12,"velocity":0.2577655539680273},{"beat":36.5,"midi":42,"duration":0.08,"velocity":0.2911793159544468},{"beat":37,"midi":42,"duration":0.08,"velocity":0.16618706753551965},{"beat":37.5,"midi":42,"duration":0.08,"velocity":0.28155436441898346},{"beat":38,"midi":42,"duration":0.08,"velocity":0.14951299550086264},{"beat":38.5,"midi":42,"duration":0.08,"velocity":0.292978693215251},{"beat":39,"midi":42,"duration":0.08,"velocity":0.16493001419603828},{"beat":39.5,"midi":42,"duration":0.08,"velocity":0.29935998227208854},{"beat":40,"midi":36,"duration":0.15,"velocity":0.6227911817951128},{"beat":42.5,"midi":36,"duration":0.15,"velocity":0.36319101423379035},{"beat":42,"midi":38,"duration":0.12,"velocity":0.2674223409183324},{"beat":40.5,"midi":42,"duration":0.08,"velocity":0.26885269566714765},{"beat":41,"midi":42,"duration":0.08,"velocity":0.14842683670371776},{"beat":41.5,"midi":42,"duration":0.08,"velocity":0.2900981490164995},{"beat":42,"midi":42,"duration":0.08,"velocity":0.15013547391891482},{"beat":42.5,"midi":42,"duration":0.08,"velocity":0.2782903241148591},{"beat":43,"midi":42,"duration":0.08,"velocity":0.15549137902855878},{"beat":43.5,"midi":42,"duration":0.08,"velocity":0.2657426358997822},{"beat":44,"midi":36,"duration":0.15,"velocity":0.6385968701584264},{"beat":46.5,"midi":36,"duration":0.15,"velocity":0.36781779395164926},{"beat":46,"midi":38,"duration":0.12,"velocity":0.2688600487709046},{"beat":44.5,"midi":42,"duration":0.08,"velocity":0.2920743362617492},{"beat":45,"midi":42,"duration":0.08,"velocity":0.1564018059819937},{"beat":45.5,"midi":42,"duration":0.08,"velocity":0.29019289072751997},{"beat":46,"midi":42,"duration":0.08,"velocity":0.1639803674280644},{"beat":46.5,"midi":42,"duration":0.08,"velocity":0.2896591020476818},{"beat":47,"midi":42,"duration":0.08,"velocity":0.15562188003957275},{"beat":47.5,"midi":42,"duration":0.08,"velocity":0.26665342630863187},{"beat":48,"midi":36,"duration":0.15,"velocity":0.6012453261822462},{"beat":50.5,"midi":36,"duration":0.15,"velocity":0.38347316287420685},{"beat":50,"midi":38,"duration":0.12,"velocity":0.29083676083944743},{"beat":48.5,"midi":42,"duration":0.08,"velocity":0.362990914780274},{"beat":49,"midi":42,"duration":0.08,"velocity":0.20171330443397167},{"beat":49.5,"midi":42,"duration":0.08,"velocity":0.37419263635911043},{"beat":50,"midi":42,"duration":0.08,"velocity":0.19364401854574684},{"beat":50.5,"midi":42,"duration":0.08,"velocity":0.33881614779643715},{"beat":51,"midi":42,"duration":0.08,"velocity":0.20576345479860905},{"beat":51.5,"midi":42,"duration":0.08,"velocity":0.3669487734172493},{"beat":52,"midi":36,"duration":0.15,"velocity":0.6033834156412632},{"beat":54.5,"midi":36,"duration":0.15,"velocity":0.3822028408040293},{"beat":54,"midi":38,"duration":0.12,"velocity":0.28975858010537925},{"beat":52.5,"midi":42,"duration":0.08,"velocity":0.33262176410481337},{"beat":53,"midi":42,"duration":0.08,"velocity":0.18739120012894273},{"beat":53.5,"midi":42,"duration":0.08,"velocity":0.3531498343728483},{"beat":54,"midi":42,"duration":0.08,"velocity":0.18867628381773832},{"beat":54.5,"midi":42,"duration":0.08,"velocity":0.3518502222105861},{"beat":55,"midi":42,"duration":0.08,"velocity":0.18627944037877026},{"beat":55.5,"midi":42,"duration":0.08,"velocity":0.37059383017010983},{"beat":56,"midi":36,"duration":0.15,"velocity":0.5981210666202008},{"beat":58.5,"midi":36,"duration":0.15,"velocity":0.3652888320416212},{"beat":58,"midi":38,"duration":0.12,"velocity":0.2608478527460248},{"beat":56.5,"midi":42,"duration":0.08,"velocity":0.3562542293228209},{"beat":57,"midi":42,"duration":0.08,"velocity":0.2005892051476985},{"beat":57.5,"midi":42,"duration":0.08,"velocity":0.3535288679033518},{"beat":58,"midi":42,"duration":0.08,"velocity":0.195253765989095},{"beat":58.5,"midi":42,"duration":0.08,"velocity":0.373120148422569},{"beat":59,"midi":42,"duration":0.08,"velocity":0.18732341896370056},{"beat":59.5,"midi":42,"duration":0.08,"velocity":0.35690220285505053},{"beat":60,"midi":36,"duration":0.15,"velocity":0.6422965398216621},{"beat":62.5,"midi":36,"duration":0.15,"velocity":0.3682552629672923},{"beat":62,"midi":38,"duration":0.12,"velocity":0.28541103162653747},{"beat":60.5,"midi":42,"duration":0.08,"velocity":0.3713737545859069},{"beat":61,"midi":42,"duration":0.08,"velocity":0.19733027558587493},{"beat":61.5,"midi":42,"duration":0.08,"velocity":0.3499408989116549},{"beat":62,"midi":42,"duration":0.08,"velocity":0.20693535734713078},{"beat":62.5,"midi":42,"duration":0.08,"velocity":0.3483866785850376},{"beat":63,"midi":42,"duration":0.08,"velocity":0.20023711827024818},{"beat":63.5,"midi":42,"duration":0.08,"velocity":0.34467739011459053}],"muted":false,"solo":false,"attack":0.008,"delay":0,"sampleRoot":60,"clips":[]}],"assets":[],"tempos":[{"beat":0,"bpm":100}],"revision":"342d70c49ff80e2a1904012cc72620dd18cb6895f813abec2b44552a989ca57f"}</script><script>!function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var r=e();for(var n in r)("object"==typeof exports?exports:t)[n]=r[n]}}("undefined"!=typeof self?self:this,(function(){return(()=>{var t={507:(t,e,r)=>{"use strict";function n(t){var e=[];return i(t,e),e}function i(t,e){for(var r=0;r<t.length;r++){var n=t[r];Array.isArray(n)?i(n,e):e.push(n)}}r.r(e),r.d(e,{flatten:()=>n})},289:(t,e,r)=>{e.parseMidi=r(666),e.writeMidi=r(865)},666:t=>{function e(t){for(var e,n=new r(t),i=[];!n.eof();){var a=o();i.push(a)}return i;function o(){var t={};t.deltaTime=n.readVarInt();var r=n.readUInt8();if(240==(240&r)){if(255!==r){if(240==r)return t.type="sysEx",a=n.readVarInt(),t.data=n.readBytes(a),t;if(247==r)return t.type="endSysEx",a=n.readVarInt(),t.data=n.readBytes(a),t;throw"Unrecognised MIDI event type byte: "+r}t.meta=!0;var i=n.readUInt8(),a=n.readVarInt();switch(i){case 0:if(t.type="sequenceNumber",2!==a)throw"Expected length for sequenceNumber event is 2, got "+a;return t.number=n.readUInt16(),t;case 1:return t.type="text",t.text=n.readString(a),t;case 2:return t.type="copyrightNotice",t.text=n.readString(a),t;case 3:return t.type="trackName",t.text=n.readString(a),t;case 4:return t.type="instrumentName",t.text=n.readString(a),t;case 5:return t.type="lyrics",t.text=n.readString(a),t;case 6:return t.type="marker",t.text=n.readString(a),t;case 7:return t.type="cuePoint",t.text=n.readString(a),t;case 32:if(t.type="channelPrefix",1!=a)throw"Expected length for channelPrefix event is 1, got "+a;return t.channel=n.readUInt8(),t;case 33:if(t.type="portPrefix",1!=a)throw"Expected length for portPrefix event is 1, got "+a;return t.port=n.readUInt8(),t;case 47:if(t.type="endOfTrack",0!=a)throw"Expected length for endOfTrack event is 0, got "+a;return t;case 81:if(t.type="setTempo",3!=a)throw"Expected length for setTempo event is 3, got "+a;return t.microsecondsPerBeat=n.readUInt24(),t;case 84:if(t.type="smpteOffset",5!=a)throw"Expected length for smpteOffset event is 5, got "+a;var o=n.readUInt8();return t.frameRate={0:24,32:25,64:29,96:30}[96&o],t.hour=31&o,t.min=n.readUInt8(),t.sec=n.readUInt8(),t.frame=n.readUInt8(),t.subFrame=n.readUInt8(),t;case 88:if(t.type="timeSignature",4!=a)throw"Expected length for timeSignature event is 4, got "+a;return t.numerator=n.readUInt8(),t.denominator=1<<n.readUInt8(),t.metronome=n.readUInt8(),t.thirtyseconds=n.readUInt8(),t;case 89:if(t.type="keySignature",2!=a)throw"Expected length for keySignature event is 2, got "+a;return t.key=n.readInt8(),t.scale=n.readUInt8(),t;case 127:return t.type="sequencerSpecific",t.data=n.readBytes(a),t;default:return t.type="unknownMeta",t.data=n.readBytes(a),t.metatypeByte=i,t}}else{var s;if(0==(128&r)){if(null===e)throw"Running status byte encountered before status byte";s=r,r=e,t.running=!0}else s=n.readUInt8(),e=r;var c=r>>4;switch(t.channel=15&r,c){case 8:return t.type="noteOff",t.noteNumber=s,t.velocity=n.readUInt8(),t;case 9:var u=n.readUInt8();return t.type=0===u?"noteOff":"noteOn",t.noteNumber=s,t.velocity=u,0===u&&(t.byte9=!0),t;case 10:return t.type="noteAftertouch",t.noteNumber=s,t.amount=n.readUInt8(),t;case 11:return t.type="controller",t.controllerType=s,t.value=n.readUInt8(),t;case 12:return t.type="programChange",t.programNumber=s,t;case 13:return t.type="channelAftertouch",t.amount=s,t;case 14:return t.type="pitchBend",t.value=s+(n.readUInt8()<<7)-8192,t;default:throw"Unrecognised MIDI event type: "+c}}}}function r(t){this.buffer=t,this.bufferLen=this.buffer.length,this.pos=0}r.prototype.eof=function(){return this.pos>=this.bufferLen},r.prototype.readUInt8=function(){var t=this.buffer[this.pos];return this.pos+=1,t},r.prototype.readInt8=function(){var t=this.readUInt8();return 128&t?t-256:t},r.prototype.readUInt16=function(){return(this.readUInt8()<<8)+this.readUInt8()},r.prototype.readInt16=function(){var t=this.readUInt16();return 32768&t?t-65536:t},r.prototype.readUInt24=function(){return(this.readUInt8()<<16)+(this.readUInt8()<<8)+this.readUInt8()},r.prototype.readInt24=function(){var t=this.readUInt24();return 8388608&t?t-16777216:t},r.prototype.readUInt32=function(){return(this.readUInt8()<<24)+(this.readUInt8()<<16)+(this.readUInt8()<<8)+this.readUInt8()},r.prototype.readBytes=function(t){var e=this.buffer.slice(this.pos,this.pos+t);return this.pos+=t,e},r.prototype.readString=function(t){var e=this.readBytes(t);return String.fromCharCode.apply(null,e)},r.prototype.readVarInt=function(){for(var t=0;!this.eof();){var e=this.readUInt8();if(!(128&e))return t+e;t+=127&e,t<<=7}return t},r.prototype.readChunk=function(){var t=this.readString(4),e=this.readUInt32();return{id:t,length:e,data:this.readBytes(e)}},t.exports=function(t){var n=new r(t),i=n.readChunk();if("MThd"!=i.id)throw"Bad MIDI file. Expected 'MHdr', got: '"+i.id+"'";for(var a=function(t){var e=new r(t),n={format:e.readUInt16(),numTracks:e.readUInt16()},i=e.readUInt16();return 32768&i?(n.framesPerSecond=256-(i>>8),n.ticksPerFrame=255&i):n.ticksPerBeat=i,n}(i.data),o=[],s=0;!n.eof()&&s<a.numTracks;s++){var c=n.readChunk();if("MTrk"!=c.id)throw"Bad MIDI file. Expected 'MTrk', got: '"+c.id+"'";var u=e(c.data);o.push(u)}return{header:a,tracks:o}}},865:t=>{function e(t,e,i){var a,o=new n,s=e.length,c=null;for(a=0;a<s;a++)!1!==i.running&&(i.running||e[a].running)||(c=null),c=r(o,e[a],c,i.useByte9ForNoteOff);t.writeChunk("MTrk",o.buffer)}function r(t,e,r,n){var i=e.type,a=e.deltaTime,o=e.text||"",s=e.data||[],c=null;switch(t.writeVarInt(a),i){case"sequenceNumber":t.writeUInt8(255),t.writeUInt8(0),t.writeVarInt(2),t.writeUInt16(e.number);break;case"text":t.writeUInt8(255),t.writeUInt8(1),t.writeVarInt(o.length),t.writeString(o);break;case"copyrightNotice":t.writeUInt8(255),t.writeUInt8(2),t.writeVarInt(o.length),t.writeString(o);break;case"trackName":t.writeUInt8(255),t.writeUInt8(3),t.writeVarInt(o.length),t.writeString(o);break;case"instrumentName":t.writeUInt8(255),t.writeUInt8(4),t.writeVarInt(o.length),t.writeString(o);break;case"lyrics":t.writeUInt8(255),t.writeUInt8(5),t.writeVarInt(o.length),t.writeString(o);break;case"marker":t.writeUInt8(255),t.writeUInt8(6),t.writeVarInt(o.length),t.writeString(o);break;case"cuePoint":t.writeUInt8(255),t.writeUInt8(7),t.writeVarInt(o.length),t.writeString(o);break;case"channelPrefix":t.writeUInt8(255),t.writeUInt8(32),t.writeVarInt(1),t.writeUInt8(e.channel);break;case"portPrefix":t.writeUInt8(255),t.writeUInt8(33),t.writeVarInt(1),t.writeUInt8(e.port);break;case"endOfTrack":t.writeUInt8(255),t.writeUInt8(47),t.writeVarInt(0);break;case"setTempo":t.writeUInt8(255),t.writeUInt8(81),t.writeVarInt(3),t.writeUInt24(e.microsecondsPerBeat);break;case"smpteOffset":t.writeUInt8(255),t.writeUInt8(84),t.writeVarInt(5);var u=31&e.hour|{24:0,25:32,29:64,30:96}[e.frameRate];t.writeUInt8(u),t.writeUInt8(e.min),t.writeUInt8(e.sec),t.writeUInt8(e.frame),t.writeUInt8(e.subFrame);break;case"timeSignature":t.writeUInt8(255),t.writeUInt8(88),t.writeVarInt(4),t.writeUInt8(e.numerator);var h=255&Math.floor(Math.log(e.denominator)/Math.LN2);t.writeUInt8(h),t.writeUInt8(e.metronome),t.writeUInt8(e.thirtyseconds||8);break;case"keySignature":t.writeUInt8(255),t.writeUInt8(89),t.writeVarInt(2),t.writeInt8(e.key),t.writeUInt8(e.scale);break;case"sequencerSpecific":t.writeUInt8(255),t.writeUInt8(127),t.writeVarInt(s.length),t.writeBytes(s);break;case"unknownMeta":null!=e.metatypeByte&&(t.writeUInt8(255),t.writeUInt8(e.metatypeByte),t.writeVarInt(s.length),t.writeBytes(s));break;case"sysEx":t.writeUInt8(240),t.writeVarInt(s.length),t.writeBytes(s);break;case"endSysEx":t.writeUInt8(247),t.writeVarInt(s.length),t.writeBytes(s);break;case"noteOff":(c=(!1!==n&&e.byte9||n&&0==e.velocity?144:128)|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.noteNumber),t.writeUInt8(e.velocity);break;case"noteOn":(c=144|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.noteNumber),t.writeUInt8(e.velocity);break;case"noteAftertouch":(c=160|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.noteNumber),t.writeUInt8(e.amount);break;case"controller":(c=176|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.controllerType),t.writeUInt8(e.value);break;case"programChange":(c=192|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.programNumber);break;case"channelAftertouch":(c=208|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.amount);break;case"pitchBend":(c=224|e.channel)!==r&&t.writeUInt8(c);var f=8192+e.value,p=127&f,l=f>>7&127;t.writeUInt8(p),t.writeUInt8(l);break;default:throw"Unrecognized event type: "+i}return c}function n(){this.buffer=[]}n.prototype.writeUInt8=function(t){this.buffer.push(255&t)},n.prototype.writeInt8=n.prototype.writeUInt8,n.prototype.writeUInt16=function(t){var e=t>>8&255,r=255&t;this.writeUInt8(e),this.writeUInt8(r)},n.prototype.writeInt16=n.prototype.writeUInt16,n.prototype.writeUInt24=function(t){var e=t>>16&255,r=t>>8&255,n=255&t;this.writeUInt8(e),this.writeUInt8(r),this.writeUInt8(n)},n.prototype.writeInt24=n.prototype.writeUInt24,n.prototype.writeUInt32=function(t){var e=t>>24&255,r=t>>16&255,n=t>>8&255,i=255&t;this.writeUInt8(e),this.writeUInt8(r),this.writeUInt8(n),this.writeUInt8(i)},n.prototype.writeInt32=n.prototype.writeUInt32,n.prototype.writeBytes=function(t){this.buffer=this.buffer.concat(Array.prototype.slice.call(t,0))},n.prototype.writeString=function(t){var e,r=t.length,n=[];for(e=0;e<r;e++)n.push(t.codePointAt(e));this.writeBytes(n)},n.prototype.writeVarInt=function(t){if(t<0)throw"Cannot write negative variable-length integer";if(t<=127)this.writeUInt8(t);else{var e=t,r=[];for(r.push(127&e),e>>=7;e;){var n=127&e|128;r.push(n),e>>=7}this.writeBytes(r.reverse())}},n.prototype.writeChunk=function(t,e){this.writeString(t),this.writeUInt32(e.length),this.writeBytes(e)},t.exports=function(t,r){if("object"!=typeof t)throw"Invalid MIDI data";r=r||{};var i,a=t.header||{},o=t.tracks||[],s=o.length,c=new n;for(function(t,e,r){var i=null==e.format?1:e.format,a=128;e.timeDivision?a=e.timeDivision:e.ticksPerFrame&&e.framesPerSecond?a=-(255&e.framesPerSecond)<<8|255&e.ticksPerFrame:e.ticksPerBeat&&(a=32767&e.ticksPerBeat);var o=new n;o.writeUInt16(i),o.writeUInt16(r),o.writeUInt16(a),t.writeChunk("MThd",o.buffer)}(c,a,s),i=0;i<s;i++)e(c,o[i],r);return c.buffer}},805:(t,e)=>{"use strict";function r(t,e,r){void 0===r&&(r="ticks");var n=0,i=t.length,a=i;if(i>0&&t[i-1][r]<=e)return i-1;for(;n<a;){var o=Math.floor(n+(a-n)/2),s=t[o],c=t[o+1];if(s[r]===e){for(var u=o;u<t.length;u++)t[u][r]===e&&(o=u);return o}if(s[r]<e&&c[r]>e)return o;s[r]>e?a=o:s[r]<e&&(n=o+1)}return-1}Object.defineProperty(e,"__esModule",{value:!0}),e.insert=e.search=void 0,e.search=r,e.insert=function(t,e,n){if(void 0===n&&(n="ticks"),t.length){var i=r(t,e[n],n);t.splice(i+1,0,e)}else t.push(e)}},543:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ControlChange=e.controlChangeIds=e.controlChangeNames=void 0,e.controlChangeNames={1:"modulationWheel",2:"breath",4:"footController",5:"portamentoTime",7:"volume",8:"balance",10:"pan",64:"sustain",65:"portamentoTime",66:"sostenuto",67:"softPedal",68:"legatoFootswitch",84:"portamentoControl"},e.controlChangeIds=Object.keys(e.controlChangeNames).reduce((function(t,r){return t[e.controlChangeNames[r]]=r,t}),{});var r=new WeakMap,n=new WeakMap,i=function(){function t(t,e){r.set(this,e),n.set(this,t.controllerType),this.ticks=t.absoluteTime,this.value=t.value}return Object.defineProperty(t.prototype,"number",{get:function(){return n.get(this)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return e.controlChangeNames[this.number]?e.controlChangeNames[this.number]:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"time",{get:function(){return r.get(this).ticksToSeconds(this.ticks)},set:function(t){var e=r.get(this);this.ticks=e.secondsToTicks(t)},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{number:this.number,ticks:this.ticks,time:this.time,value:this.value}},t}();e.ControlChange=i},906:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createControlChanges=void 0;var n=r(543);e.createControlChanges=function(){return new Proxy({},{get:function(t,e){return t[e]?t[e]:n.controlChangeIds.hasOwnProperty(e)?t[n.controlChangeIds[e]]:void 0},set:function(t,e,r){return n.controlChangeIds.hasOwnProperty(e)?t[n.controlChangeIds[e]]=r:t[e]=r,!0}})}},54:function(t,e,r){"use strict";var n=this&&this.__spreadArray||function(t,e,r){if(r||2===arguments.length)for(var n,i=0,a=e.length;i<a;i++)!n&&i in e||(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))};Object.defineProperty(e,"__esModule",{value:!0}),e.encode=void 0;var i=r(289),a=r(535),o=r(507);function s(t,e){return{absoluteTime:t.ticks,channel:e,controllerType:t.number,deltaTime:0,type:"controller",value:Math.floor(127*t.value)}}function c(t){return{absoluteTime:0,channel:t.channel,deltaTime:0,programNumber:t.instrument.number,type:"programChange"}}e.encode=function(t){var e={header:{format:1,numTracks:t.tracks.length+1,ticksPerBeat:t.header.ppq},tracks:n([n(n(n(n([{absoluteTime:0,deltaTime:0,meta:!0,text:t.header.name,type:"trackName"}],t.header.keySignatures.map((function(t){return function(t){var e=a.keySignatureKeys.indexOf(t.key);return{absoluteTime:t.ticks,deltaTime:0,key:e+7,meta:!0,scale:"major"===t.scale?0:1,type:"keySignature"}}(t)})),!0),t.header.meta.map((function(t){return{absoluteTime:(e=t).ticks,deltaTime:0,meta:!0,text:e.text,type:e.type};var e})),!0),t.header.tempos.map((function(t){return function(t){return{absoluteTime:t.ticks,deltaTime:0,meta:!0,microsecondsPerBeat:Math.floor(6e7/t.bpm),type:"setTempo"}}(t)})),!0),t.header.timeSignatures.map((function(t){return function(t){return{absoluteTime:t.ticks,deltaTime:0,denominator:t.timeSignature[1],meta:!0,metronome:24,numerator:t.timeSignature[0],thirtyseconds:8,type:"timeSignature"}}(t)})),!0)],t.tracks.map((function(t){return n(n(n([(e=t.name,{absoluteTime:0,deltaTime:0,meta:!0,text:e,type:"trackName"}),c(t)],function(t){return(0,o.flatten)(t.notes.map((function(e){return function(t,e){return[{absoluteTime:t.ticks,channel:e,deltaTime:0,noteNumber:t.midi,type:"noteOn",velocity:Math.floor(127*t.velocity)},{absoluteTime:t.ticks+t.durationTicks,channel:e,deltaTime:0,noteNumber:t.midi,type:"noteOff",velocity:Math.floor(127*t.noteOffVelocity)}]}(e,t.channel)})))}(t),!0),function(t){for(var e=[],r=0;r<127;r++)t.controlChanges.hasOwnProperty(r)&&t.controlChanges[r].forEach((function(r){e.push(s(r,t.channel))}));return e}(t),!0),function(t){var e=[];return t.pitchBends.forEach((function(r){e.push(function(t,e){return{absoluteTime:t.ticks,channel:e,deltaTime:0,type:"pitchBend",value:t.value}}(r,t.channel))})),e}(t),!0);var e})),!0)};return e.tracks=e.tracks.map((function(t){t=t.sort((function(t,e){return t.absoluteTime-e.absoluteTime}));var e=0;return t.forEach((function(t){t.deltaTime=t.absoluteTime-e,e=t.absoluteTime,delete t.absoluteTime})),t.push({deltaTime:0,meta:!0,type:"endOfTrack"}),t})),new Uint8Array((0,i.writeMidi)(e))}},535:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Header=e.keySignatureKeys=void 0;var n=r(805),i=new WeakMap;e.keySignatureKeys=["Cb","Gb","Db","Ab","Eb","Bb","F","C","G","D","A","E","B","F#","C#"];var a=function(){function t(t){var r=this;if(this.tempos=[],this.timeSignatures=[],this.keySignatures=[],this.meta=[],this.name="",i.set(this,480),t){i.set(this,t.header.ticksPerBeat),t.tracks.forEach((function(t){t.forEach((function(t){t.meta&&("timeSignature"===t.type?r.timeSignatures.push({ticks:t.absoluteTime,timeSignature:[t.numerator,t.denominator]}):"setTempo"===t.type?r.tempos.push({bpm:6e7/t.microsecondsPerBeat,ticks:t.absoluteTime}):"keySignature"===t.type&&r.keySignatures.push({key:e.keySignatureKeys[t.key+7],scale:0===t.scale?"major":"minor",ticks:t.absoluteTime}))}))}));var n=0;t.tracks[0].forEach((function(t){n+=t.deltaTime,t.meta&&("trackName"===t.type?r.name=t.text:"text"!==t.type&&"cuePoint"!==t.type&&"marker"!==t.type&&"lyrics"!==t.type||r.meta.push({text:t.text,ticks:n,type:t.type}))})),this.update()}}return t.prototype.update=function(){var t=this,e=0,r=0;this.tempos.sort((function(t,e){return t.ticks-e.ticks})),this.tempos.forEach((function(n,i){var a=i>0?t.tempos[i-1].bpm:t.tempos[0].bpm,o=n.ticks/t.ppq-r,s=60/a*o;n.time=s+e,e=n.time,r+=o})),this.timeSignatures.sort((function(t,e){return t.ticks-e.ticks})),this.timeSignatures.forEach((function(e,r){var n=r>0?t.timeSignatures[r-1]:t.timeSignatures[0],i=(e.ticks-n.ticks)/t.ppq/n.timeSignature[0]/(n.timeSignature[1]/4);n.measures=n.measures||0,e.measures=i+n.measures}))},t.prototype.ticksToSeconds=function(t){var e=(0,n.search)(this.tempos,t);if(-1!==e){var r=this.tempos[e],i=r.time,a=(t-r.ticks)/this.ppq;return i+60/r.bpm*a}return t/this.ppq*.5},t.prototype.ticksToMeasures=function(t){var e=(0,n.search)(this.timeSignatures,t);if(-1!==e){var r=this.timeSignatures[e],i=(t-r.ticks)/this.ppq;return r.measures+i/(r.timeSignature[0]/r.timeSignature[1])/4}return t/this.ppq/4},Object.defineProperty(t.prototype,"ppq",{get:function(){return i.get(this)},enumerable:!1,configurable:!0}),t.prototype.secondsToTicks=function(t){var e=(0,n.search)(this.tempos,t,"time");if(-1!==e){var r=this.tempos[e],i=(t-r.time)/(60/r.bpm);return Math.round(r.ticks+i*this.ppq)}var a=t/.5;return Math.round(a*this.ppq)},t.prototype.toJSON=function(){return{keySignatures:this.keySignatures,meta:this.meta,name:this.name,ppq:this.ppq,tempos:this.tempos.map((function(t){return{bpm:t.bpm,ticks:t.ticks}})),timeSignatures:this.timeSignatures}},t.prototype.fromJSON=function(t){this.name=t.name,this.tempos=t.tempos.map((function(t){return Object.assign({},t)})),this.timeSignatures=t.timeSignatures.map((function(t){return Object.assign({},t)})),this.keySignatures=t.keySignatures.map((function(t){return Object.assign({},t)})),this.meta=t.meta.map((function(t){return Object.assign({},t)})),i.set(this,t.ppq),this.update()},t.prototype.setTempo=function(t){this.tempos=[{bpm:t,ticks:0}],this.update()},t}();e.Header=a},362:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Instrument=void 0;var n=r(438),i=new WeakMap,a=function(){function t(t,e){if(this.number=0,i.set(this,e),this.number=0,t){var r=t.find((function(t){return"programChange"===t.type}));r&&(this.number=r.programNumber)}}return Object.defineProperty(t.prototype,"name",{get:function(){return this.percussion?n.DrumKitByPatchID[this.number]:n.instrumentByPatchID[this.number]},set:function(t){var e=n.instrumentByPatchID.indexOf(t);-1!==e&&(this.number=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"family",{get:function(){return this.percussion?"drums":n.InstrumentFamilyByID[Math.floor(this.number/8)]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"percussion",{get:function(){return 9===i.get(this).channel},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{family:this.family,number:this.number,name:this.name}},t.prototype.fromJSON=function(t){this.number=t.number},t}();e.Instrument=a},438:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.DrumKitByPatchID=e.InstrumentFamilyByID=e.instrumentByPatchID=void 0,e.instrumentByPatchID=["acoustic grand piano","bright acoustic piano","electric grand piano","honky-tonk piano","electric piano 1","electric piano 2","harpsichord","clavi","celesta","glockenspiel","music box","vibraphone","marimba","xylophone","tubular bells","dulcimer","drawbar organ","percussive organ","rock organ","church organ","reed organ","accordion","harmonica","tango accordion","acoustic guitar (nylon)","acoustic guitar (steel)","electric guitar (jazz)","electric guitar (clean)","electric guitar (muted)","overdriven guitar","distortion guitar","guitar harmonics","acoustic bass","electric bass (finger)","electric bass (pick)","fretless bass","slap bass 1","slap bass 2","synth bass 1","synth bass 2","violin","viola","cello","contrabass","tremolo strings","pizzicato strings","orchestral harp","timpani","string ensemble 1","string ensemble 2","synthstrings 1","synthstrings 2","choir aahs","voice oohs","synth voice","orchestra hit","trumpet","trombone","tuba","muted trumpet","french horn","brass section","synthbrass 1","synthbrass 2","soprano sax","alto sax","tenor sax","baritone sax","oboe","english horn","bassoon","clarinet","piccolo","flute","recorder","pan flute","blown bottle","shakuhachi","whistle","ocarina","lead 1 (square)","lead 2 (sawtooth)","lead 3 (calliope)","lead 4 (chiff)","lead 5 (charang)","lead 6 (voice)","lead 7 (fifths)","lead 8 (bass + lead)","pad 1 (new age)","pad 2 (warm)","pad 3 (polysynth)","pad 4 (choir)","pad 5 (bowed)","pad 6 (metallic)","pad 7 (halo)","pad 8 (sweep)","fx 1 (rain)","fx 2 (soundtrack)","fx 3 (crystal)","fx 4 (atmosphere)","fx 5 (brightness)","fx 6 (goblins)","fx 7 (echoes)","fx 8 (sci-fi)","sitar","banjo","shamisen","koto","kalimba","bag pipe","fiddle","shanai","tinkle bell","agogo","steel drums","woodblock","taiko drum","melodic tom","synth drum","reverse cymbal","guitar fret noise","breath noise","seashore","bird tweet","telephone ring","helicopter","applause","gunshot"],e.InstrumentFamilyByID=["piano","chromatic percussion","organ","guitar","bass","strings","ensemble","brass","reed","pipe","synth lead","synth pad","synth effects","world","percussive","sound effects"],e.DrumKitByPatchID={0:"standard kit",8:"room kit",16:"power kit",24:"electronic kit",25:"tr-808 kit",32:"jazz kit",40:"brush kit",48:"orchestra kit",56:"sound fx kit"}},233:function(t,e,r){"use strict";var n=this&&this.__awaiter||function(t,e,r,n){return new(r||(r=Promise))((function(i,a){function o(t){try{c(n.next(t))}catch(t){a(t)}}function s(t){try{c(n.throw(t))}catch(t){a(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(o,s)}c((n=n.apply(t,e||[])).next())}))},i=this&&this.__generator||function(t,e){var r,n,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=e.call(t,o)}catch(t){a=[6,t],n=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}};Object.defineProperty(e,"__esModule",{value:!0}),e.Header=e.Track=e.Midi=void 0;var a=r(289),o=r(535),s=r(334),c=r(54),u=function(){function t(t){var e=this,r=null;if(t){var n=t instanceof ArrayBuffer?new Uint8Array(t):t;(r=(0,a.parseMidi)(n)).tracks.forEach((function(t){var e=0;t.forEach((function(t){e+=t.deltaTime,t.absoluteTime=e}))})),r.tracks=function(t){for(var e=[],r=0;r<t.length;r++)for(var n=e.length,i=new Map,a=Array(16).fill(0),o=0,s=t[r];o<s.length;o++){var c=s[o],u=n,h=c.channel;if(void 0!==h){"programChange"===c.type&&(a[h]=c.programNumber);var f=a[h],p="".concat(f," ").concat(h);i.has(p)?u=i.get(p):(u=n+i.size,i.set(p,u))}e[u]||e.push([]),e[u].push(c)}return e}(r.tracks)}this.header=new o.Header(r),this.tracks=[],t&&(this.tracks=r.tracks.map((function(t){return new s.Track(t,e.header)})),1===r.header.format&&0===this.tracks[0].duration&&this.tracks.shift())}return t.fromUrl=function(e){return n(this,void 0,void 0,(function(){var r;return i(this,(function(n){switch(n.label){case 0:return[4,fetch(e)];case 1:return(r=n.sent()).ok?[4,r.arrayBuffer()]:[3,3];case 2:return[2,new t(n.sent())];case 3:throw new Error("Could not load '".concat(e,"'"))}}))}))},Object.defineProperty(t.prototype,"name",{get:function(){return this.header.name},set:function(t){this.header.name=t},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"duration",{get:function(){var t=this.tracks.map((function(t){return t.duration}));return Math.max.apply(Math,t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"durationTicks",{get:function(){var t=this.tracks.map((function(t){return t.durationTicks}));return Math.max.apply(Math,t)},enumerable:!1,configurable:!0}),t.prototype.addTrack=function(){var t=new s.Track(void 0,this.header);return this.tracks.push(t),t},t.prototype.toArray=function(){return(0,c.encode)(this)},t.prototype.toJSON=function(){return{header:this.header.toJSON(),tracks:this.tracks.map((function(t){return t.toJSON()}))}},t.prototype.fromJSON=function(t){var e=this;this.header=new o.Header,this.header.fromJSON(t.header),this.tracks=t.tracks.map((function(t){var r=new s.Track(void 0,e.header);return r.fromJSON(t),r}))},t.prototype.clone=function(){var e=new t;return e.fromJSON(this.toJSON()),e},t}();e.Midi=u;var h=r(334);Object.defineProperty(e,"Track",{enumerable:!0,get:function(){return h.Track}});var f=r(535);Object.defineProperty(e,"Header",{enumerable:!0,get:function(){return f.Header}})},518:(t,e)=>{"use strict";function r(t){return["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"][t%12]}Object.defineProperty(e,"__esModule",{value:!0}),e.Note=void 0;var n,i,a=(n=/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,i={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},function(t){var e=n.exec(t),r=e[1],a=e[2];return i[r.toLowerCase()]+12*(parseInt(a,10)+1)}),o=new WeakMap,s=function(){function t(t,e,r){o.set(this,r),this.midi=t.midi,this.velocity=t.velocity,this.noteOffVelocity=e.velocity,this.ticks=t.ticks,this.durationTicks=e.ticks-t.ticks}return Object.defineProperty(t.prototype,"name",{get:function(){return t=this.midi,e=Math.floor(t/12)-1,r(t)+e.toString();var t,e},set:function(t){this.midi=a(t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"octave",{get:function(){return Math.floor(this.midi/12)-1},set:function(t){var e=t-this.octave;this.midi+=12*e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pitch",{get:function(){return r(this.midi)},set:function(t){this.midi=12*(this.octave+1)+["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"].indexOf(t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"duration",{get:function(){var t=o.get(this);return t.ticksToSeconds(this.ticks+this.durationTicks)-t.ticksToSeconds(this.ticks)},set:function(t){var e=o.get(this).secondsToTicks(this.time+t);this.durationTicks=e-this.ticks},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"time",{get:function(){return o.get(this).ticksToSeconds(this.ticks)},set:function(t){var e=o.get(this);this.ticks=e.secondsToTicks(t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bars",{get:function(){return o.get(this).ticksToMeasures(this.ticks)},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{duration:this.duration,durationTicks:this.durationTicks,midi:this.midi,name:this.name,ticks:this.ticks,time:this.time,velocity:this.velocity}},t}();e.Note=s},882:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PitchBend=void 0;var r=new WeakMap,n=function(){function t(t,e){r.set(this,e),this.ticks=t.absoluteTime,this.value=t.value}return Object.defineProperty(t.prototype,"time",{get:function(){return r.get(this).ticksToSeconds(this.ticks)},set:function(t){var e=r.get(this);this.ticks=e.secondsToTicks(t)},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{ticks:this.ticks,time:this.time,value:this.value}},t}();e.PitchBend=n},334:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Track=void 0;var n=r(805),i=r(543),a=r(906),o=r(882),s=r(362),c=r(518),u=new WeakMap,h=function(){function t(t,e){var r=this;if(this.name="",this.notes=[],this.controlChanges=(0,a.createControlChanges)(),this.pitchBends=[],u.set(this,e),t){var n=t.find((function(t){return"trackName"===t.type}));this.name=n?n.text:""}if(this.instrument=new s.Instrument(t,this),this.channel=0,t){for(var i=t.filter((function(t){return"noteOn"===t.type})),o=t.filter((function(t){return"noteOff"===t.type})),c=function(){var t=i.shift();h.channel=t.channel;var e=o.findIndex((function(e){return e.noteNumber===t.noteNumber&&e.absoluteTime>=t.absoluteTime}));if(-1!==e){var r=o.splice(e,1)[0];h.addNote({durationTicks:r.absoluteTime-t.absoluteTime,midi:t.noteNumber,noteOffVelocity:r.velocity/127,ticks:t.absoluteTime,velocity:t.velocity/127})}},h=this;i.length;)c();t.filter((function(t){return"controller"===t.type})).forEach((function(t){r.addCC({number:t.controllerType,ticks:t.absoluteTime,value:t.value/127})})),t.filter((function(t){return"pitchBend"===t.type})).forEach((function(t){r.addPitchBend({ticks:t.absoluteTime,value:t.value/Math.pow(2,13)})}));var f=t.find((function(t){return"endOfTrack"===t.type}));this.endOfTrackTicks=void 0!==f?f.absoluteTime:void 0}}return t.prototype.addNote=function(t){var e=u.get(this),r=new c.Note({midi:0,ticks:0,velocity:1},{ticks:0,velocity:0},e);return Object.assign(r,t),(0,n.insert)(this.notes,r,"ticks"),this},t.prototype.addCC=function(t){var e=u.get(this),r=new i.ControlChange({controllerType:t.number},e);return delete t.number,Object.assign(r,t),Array.isArray(this.controlChanges[r.number])||(this.controlChanges[r.number]=[]),(0,n.insert)(this.controlChanges[r.number],r,"ticks"),this},t.prototype.addPitchBend=function(t){var e=u.get(this),r=new o.PitchBend({},e);return Object.assign(r,t),(0,n.insert)(this.pitchBends,r,"ticks"),this},Object.defineProperty(t.prototype,"duration",{get:function(){if(!this.notes.length)return 0;for(var t=this.notes[this.notes.length-1].time+this.notes[this.notes.length-1].duration,e=0;e<this.notes.length-1;e++){var r=this.notes[e].time+this.notes[e].duration;t<r&&(t=r)}return t},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"durationTicks",{get:function(){if(!this.notes.length)return 0;for(var t=this.notes[this.notes.length-1].ticks+this.notes[this.notes.length-1].durationTicks,e=0;e<this.notes.length-1;e++){var r=this.notes[e].ticks+this.notes[e].durationTicks;t<r&&(t=r)}return t},enumerable:!1,configurable:!0}),t.prototype.fromJSON=function(t){var e=this;for(var r in this.name=t.name,this.channel=t.channel,this.instrument=new s.Instrument(void 0,this),this.instrument.fromJSON(t.instrument),void 0!==t.endOfTrackTicks&&(this.endOfTrackTicks=t.endOfTrackTicks),t.controlChanges)t.controlChanges[r]&&t.controlChanges[r].forEach((function(t){e.addCC({number:t.number,ticks:t.ticks,value:t.value})}));t.notes.forEach((function(t){e.addNote({durationTicks:t.durationTicks,midi:t.midi,ticks:t.ticks,velocity:t.velocity})}))},t.prototype.toJSON=function(){for(var t={},e=0;e<127;e++)this.controlChanges.hasOwnProperty(e)&&(t[e]=this.controlChanges[e].map((function(t){return t.toJSON()})));var r={channel:this.channel,controlChanges:t,pitchBends:this.pitchBends.map((function(t){return t.toJSON()})),instrument:this.instrument.toJSON(),name:this.name,notes:this.notes.map((function(t){return t.toJSON()}))};return void 0!==this.endOfTrackTicks&&(r.endOfTrackTicks=this.endOfTrackTicks),r},t}();e.Track=h}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var a=e[n]={exports:{}};return t[n].call(a.exports,a,a.exports,r),a.exports}return r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r(233)})()}));
</script><script id="afterhours-model">const MUSIC_SPEC = 'afterhours/1';
const instruments = { felt: 'Felt keys', pluck: 'Plucked strings', pad: 'Analog pad', bass: 'Round bass', bell: 'Glass bells', lead: 'Soft lead', drums: 'Drum kit', sampler: 'Your sample', audio: 'Audio recording' };
const midiPrograms = { felt: 0, pluck: 24, pad: 89, bass: 33, bell: 11, lead: 80, drums: 0, sampler: 0, audio: 0 };
const finite = (value, min, max) => Number.isFinite(value) && value >= min && value <= max;
function validateSession(input) {
const p = structuredClone(input);
if (!p || p.spec !== MUSIC_SPEC) throw new Error('Open an Afterhours project.');
if (typeof p.id !== 'string' || !/^[a-z0-9-]{1,80}$/.test(p.id)) throw new Error('Project needs a stable id.');
if (typeof p.title !== 'string' || !p.title.trim() || p.title.length > 160 || typeof p.brief !== 'string' || p.brief.length > 6000) throw new Error('Name the piece and its brief.');
p.seed = String(p.seed ?? '1').slice(0, 128);
if (!finite(p.tempo, 30, 240)) throw new Error('Tempo must be 30–240 BPM.');
p.tempos ??= [{ beat: 0, bpm: p.tempo }];
if (!Array.isArray(p.tempos) || !p.tempos.length || p.tempos.length > 200 || p.tempos[0].beat !== 0) throw new Error('Tempo map must begin at beat zero.');
for (let i = 0; i < p.tempos.length; i++) if (!finite(p.tempos[i].beat, 0, 4096) || !finite(p.tempos[i].bpm, 30, 240) || i && p.tempos[i].beat <= p.tempos[i - 1].beat) throw new Error('Tempo changes must be ordered and valid.');
p.tempo = p.tempos[0].bpm;
p.meter ??= [4, 4];
if (!Array.isArray(p.meter) || !Number.isInteger(p.meter[0]) || !finite(p.meter[0], 1, 12) || ![2, 4, 8, 16].includes(p.meter[1])) throw new Error('Invalid time signature.');
if (!finite(p.beats, 1, 4096) || secondsAt(p, p.beats) > 240) throw new Error('Keep a piece within four minutes; split longer work into movements.');
p.master ??= .85; if (!finite(p.master, 0, 1)) throw new Error('Invalid master level.');
p.tail ??= 1.5; if (!finite(p.tail, 0, 6)) throw new Error('Use a tail of 0–6 seconds.');
p.assets ??= [];
const assets = new Set();
if (!Array.isArray(p.assets) || p.assets.length > 16) throw new Error('Use at most 16 audio assets.');
for (const a of p.assets) {
if (typeof a.id !== 'string' || assets.has(a.id) || typeof a.name !== 'string' || a.name.length > 200 || typeof a.data !== 'string' || !/^data:(audio\/[a-z0-9.+-]+|application\/octet-stream);base64,[a-zA-Z0-9+/=]+$/i.test(a.data)) throw new Error('Audio assets must be embedded recordings.');
assets.add(a.id);
}
if (!Array.isArray(p.tracks) || !p.tracks.length || p.tracks.length > 16) throw new Error('Use 1–16 tracks.');
const trackIds = new Set(); let noteCount = 0;
for (const t of p.tracks) {
if (typeof t.id !== 'string' || trackIds.has(t.id) || typeof t.name !== 'string' || t.name.length > 120 || !Object.hasOwn(instruments, t.instrument)) throw new Error('Invalid track.');
trackIds.add(t.id);
const defaults = { gain: .7, pan: 0, muted: false, solo: false, attack: .008, release: .25, tone: 8000, space: .12, delay: 0, sampleRoot: 60 };
for (const [key, value] of Object.entries(defaults)) t[key] ??= value;
for (const [key, low, high] of [['gain', 0, 1.5], ['pan', -1, 1], ['attack', .001, 3], ['release', .01, 3], ['tone', 100, 20000], ['space', 0, .8], ['delay', 0, .6], ['sampleRoot', 0, 127]]) if (!finite(t[key], low, high)) throw new Error(`Invalid ${t.name}: ${key}.`);
if (typeof t.muted !== 'boolean' || typeof t.solo !== 'boolean') throw new Error('Invalid mute/solo state.');
if (t.midiProgram !== undefined && (!Number.isInteger(t.midiProgram) || !finite(t.midiProgram, 0, 127))) throw new Error('Invalid MIDI program.');
t.notes ??= []; t.clips ??= [];
if (!Array.isArray(t.notes) || !Array.isArray(t.clips) || t.clips.length > 100) throw new Error('Invalid track events.');
noteCount += t.notes.length;
for (const n of t.notes) if (!finite(n.beat, 0, p.beats) || !finite(n.duration, 1 / 32767, p.beats) || n.beat + n.duration > p.beats + 1e-6 || !Number.isInteger(n.midi) || !finite(n.midi, 0, 127) || !finite(n.velocity, 1 / 127, 1)) throw new Error(`Invalid note in ${t.name}. Use a positive MIDI velocity (at least 1/127); mute the track for silence.`);
if (t.instrument === 'audio' && t.notes.length) throw new Error('Choose an instrument to play MIDI notes on this track.');
if (t.instrument === 'sampler' && !assets.has(t.sampleId)) throw new Error(`Choose a sample for ${t.name}.`);
for (const c of t.clips) {
c.gain ??= 1; c.fadeIn ??= .02; c.fadeOut ??= .05;
if (!assets.has(c.assetId) || !finite(c.beat, 0, p.beats) || !finite(c.offset, 0, 240) || !finite(c.duration, .01, 240) || !finite(c.gain, 0, 1.5) || !finite(c.fadeIn, 0, c.duration) || !finite(c.fadeOut, 0, c.duration)) throw new Error(`Invalid audio clip in ${t.name}.`);
if (secondsAt(p, c.beat) + c.duration > secondsAt(p, p.beats) + .001) throw new Error(`Extend the arrangement to fit ${t.name}'s recording.`);
}
}
if (noteCount > 16000) throw new Error('Use at most 16,000 notes per piece.');
p.sections ??= [{ name: 'Piece', beat: 0, length: p.beats }];
if (!Array.isArray(p.sections) || p.sections.length > 64) throw new Error('Invalid arrangement sections.');
for (const s of p.sections) if (typeof s.name !== 'string' || s.name.length > 80 || !finite(s.beat, 0, p.beats) || !finite(s.length, .01, p.beats) || s.beat + s.length > p.beats + 1e-6) throw new Error('Sections must fit inside the piece.');
if (JSON.stringify(p).length > 28000000) throw new Error('Keep the project under 28 MB. For long recordings, import an MP3 or a shorter WAV.');
return p;
}
function beatsPerBar(p) { return p.meter[0] * 4 / p.meter[1]; }
function secondsAt(p, beat) {
const map = p.tempos || [{ beat: 0, bpm: p.tempo }]; let seconds = 0;
for (let i = 0; i < map.length && map[i].beat < beat; i++) seconds += (Math.min(beat, map[i + 1]?.beat ?? beat) - map[i].beat) * 60 / map[i].bpm;
return seconds;
}
function beatAt(p, seconds) {
const map = p.tempos || [{ beat: 0, bpm: p.tempo }]; let elapsed = 0;
for (let i = 0; i < map.length; i++) {
const length = ((map[i + 1]?.beat ?? Infinity) - map[i].beat) * 60 / map[i].bpm;
if (elapsed + length >= seconds) return map[i].beat + (seconds - elapsed) * map[i].bpm / 60;
elapsed += length;
}
return 0;
}
function noteName(n) { return ['C', 'C♯', 'D', 'D♯', 'E', 'F', 'F♯', 'G', 'G♯', 'A', 'A♯', 'B'][n % 12] + (Math.floor(n / 12) - 1); }
function noteNumber(name) {
if (typeof name === 'number') return name;
const m = /^([A-Ga-g])([#b♯♭]?)(-?\d+)$/.exec(name.trim());
if (!m) throw new Error('Use a pitch such as C4, F#3 or Bb5.');
return (Number(m[3]) + 1) * 12 + ({ C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 })[m[1].toUpperCase()] + (['#', '♯'].includes(m[2]) ? 1 : ['b', '♭'].includes(m[2]) ? -1 : 0);
}
function musicRandom(seed) {
let n = 2166136261; for (const c of String(seed)) n = Math.imul(n ^ c.charCodeAt(0), 16777619);
return () => { n += 0x6d2b79f5; let t = Math.imul(n ^ n >>> 15, n | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); return ((t ^ t >>> 14) >>> 0) / 4294967296; };
}
function activeTracks(p) { const solo = p.tracks.some(t => t.solo); return p.tracks.filter(t => !t.muted && (!solo || t.solo)); }
function duplicateSection(p, start, length) {
if (!finite(start, 0, p.beats) || !finite(length, .25, p.beats) || start + length > p.beats) throw new Error('Select a section within the piece.');
const next = structuredClone(p), destination = p.beats;
for (const t of next.tracks) {
const notes = t.notes.filter(n => n.beat >= start && n.beat < start + length).map(n => ({ ...n, beat: n.beat - start + destination, duration: Math.min(n.duration, start + length - n.beat) }));
const clips = t.clips.filter(c => c.beat >= start && c.beat < start + length).map(c => ({ ...c, beat: c.beat - start + destination, duration: Math.min(c.duration, secondsAt(p, start + length) - secondsAt(p, c.beat)) }));
t.notes.push(...notes); t.clips.push(...clips);
}
next.beats += length;
const initial = p.tempos.filter(t => t.beat <= start).at(-1).bpm;
if (next.tempos.at(-1).bpm !== initial) next.tempos.push({ beat: destination, bpm: initial });
next.tempos.push(...p.tempos.filter(t => t.beat > start && t.beat < start + length).map(t => ({ beat: destination + t.beat - start, bpm: t.bpm })));
next.sections.push({ name: 'New section', beat: destination, length });
return validateSession(next);
}
function writeSessionMidi(p, MidiClass) {
if (p.tracks.filter(t => t.notes.length && t.instrument !== 'drums').length > 15) throw new Error('MIDI has 15 melodic channels plus drums. Combine a melodic track or export WAV stems.');
const midi = new MidiClass(); midi.header.name = p.title;
midi.header.tempos = p.tempos.map(t => ({ ticks: Math.round(t.beat * midi.header.ppq), bpm: t.bpm }));
// Standard markers preserve section cues and intentional silence at the end.
// The encoder otherwise ends the file at the final note-off.
midi.header.meta = [...p.sections.map(s => ({ ticks: Math.round(s.beat * midi.header.ppq), type: 'marker', text: s.name })), { ticks: Math.round(p.beats * midi.header.ppq), type: 'marker', text: 'Afterhours: end' }];
midi.header.timeSignatures = [{ ticks: 0, timeSignature: p.meter }]; midi.header.update();
let channel = 0;
for (const t of p.tracks.filter(t => t.notes.length)) {
const track = midi.addTrack(); track.name = t.name;
if (channel === 9) channel++;
track.channel = t.instrument === 'drums' ? 9 : channel++ % 16;
track.instrument.number = t.midiProgram ?? midiPrograms[t.instrument];
track.addCC({ number: 7, ticks: 0, value: Math.min(1, t.gain) }); track.addCC({ number: 10, ticks: 0, value: (t.pan + 1) / 2 });
for (const n of t.notes) track.addNote({ midi: n.midi, ticks: Math.round(n.beat * midi.header.ppq), durationTicks: Math.max(1, Math.round(n.duration * midi.header.ppq)), velocity: n.velocity });
}
return midi.toArray();
}
function readSessionMidi(bytes, MidiClass) {
const midi = new MidiClass(bytes), warnings = [], ppq = midi.header.ppq;
const source = midi.tracks.filter(t => t.notes.length);
if (!source.length) throw new Error('That MIDI file contains no notes.');
if (midi.header.timeSignatures.length > 1) throw new Error('This studio supports one time signature per piece. Split meter changes into movements before importing.');
const tempos = midi.header.tempos.map(t => ({ beat: t.ticks / ppq, bpm: t.bpm }));
if (!tempos.length || tempos[0].beat !== 0) tempos.unshift({ beat: 0, bpm: 120 });
const meter = midi.header.timeSignatures[0]?.timeSignature || [4, 4], bar = meter[0] * 4 / meter[1];
const tracks = source.map((t, i) => {
if (Object.entries(t.controlChanges).some(([key, events]) => events?.some(e => !['7', '10'].includes(key) || e.ticks !== 0)) || t.pitchBends.length) warnings.push(`${t.name || 'Track ' + (i + 1)}: MIDI automation and pitch bends are not imported. Render audio in the source application if they are essential.`);
const program = t.instrument.number;
const instrument = t.instrument.percussion ? 'drums' : program >= 32 && program <= 39 ? 'bass' : program >= 24 && program <= 31 ? 'pluck' : program >= 88 && program <= 95 ? 'pad' : program >= 8 && program <= 15 ? 'bell' : 'felt';
return { id: 'midi-' + i, name: (t.name || t.instrument.name || 'Track ' + (i + 1)).slice(0, 120), instrument, midiProgram: program, gain: t.controlChanges[7]?.find(e => e.ticks === 0)?.value ?? .7, pan: (t.controlChanges[10]?.find(e => e.ticks === 0)?.value ?? .5) * 2 - 1, notes: t.notes.map(n => ({ beat: n.ticks / ppq, duration: Math.max(1, n.durationTicks) / ppq, midi: n.midi, velocity: n.velocity })) };
});
const lastTick = Math.max(0, ...midi.header.meta.map(m => m.ticks), ...midi.tracks.map(t => t.endOfTrackTicks || 0));
const beats = Math.ceil(Math.max(lastTick / ppq, ...tracks.flatMap(t => t.notes.map(n => n.beat + n.duration))) / bar) * bar;
return validateSession({ spec: MUSIC_SPEC, id: 'imported-midi', title: (midi.name || 'Your composition').slice(0, 160), brief: 'Your MIDI notes and tempo map, ready to arrange and produce. Synthesized instruments are a preview; export MIDI or stems to continue in your DAW.', seed: 'midi', tempo: tempos[0].bpm, tempos, meter, beats, tracks, importWarnings: warnings });
}
function wavBytes(channels, sampleRate, gain = 1) {
const frames = channels[0].length, count = channels.length;
const bytes = new ArrayBuffer(44 + frames * count * 2), view = new DataView(bytes);
const text = (at, s) => [...s].forEach((c, i) => view.setUint8(at + i, c.charCodeAt(0)));
text(0, 'RIFF'); view.setUint32(4, bytes.byteLength - 8, true); text(8, 'WAVE'); text(12, 'fmt '); view.setUint32(16, 16, true);
view.setUint16(20, 1, true); view.setUint16(22, count, true); view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * count * 2, true); view.setUint16(32, count * 2, true); view.setUint16(34, 16, true); text(36, 'data'); view.setUint32(40, frames * count * 2, true);
for (let i = 0; i < frames; i++) for (let c = 0; c < count; c++) view.setInt16(44 + (i * count + c) * 2, Math.round(Math.max(-1, Math.min(1, channels[c][i] * gain)) * 32767), true);
return bytes;
}
</script><script>const decoded = new Map();
async function audioAssets(project, context) {
const result = new Map();
for (const asset of project.assets) {
let buffer = decoded.get(asset.data);
if (!buffer) {
const binary = atob(asset.data.split(',')[1]), bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
try { buffer = await context.decodeAudioData(bytes.buffer); }
catch { throw new Error(`Cannot decode ${asset.name}. Use a WAV or MP3 recording.`); }
if (buffer.duration > 240) throw new Error(`${asset.name} is longer than four minutes. Trim it before importing.`);
if (decoded.size >= 16) decoded.delete(decoded.keys().next().value);
decoded.set(asset.data, buffer);
}
result.set(asset.id, buffer);
}
return result;
}
function noiseBuffer(context, seed, seconds) {
const buffer = context.createBuffer(1, Math.ceil(context.sampleRate * seconds), context.sampleRate), data = buffer.getChannelData(0), r = musicRandom(seed);
for (let i = 0; i < data.length; i++) data[i] = r() * 2 - 1;
return buffer;
}
function impulse(context, seed) {
const length = Math.round(context.sampleRate * 1.4), buffer = context.createBuffer(2, length, context.sampleRate), r = musicRandom(seed);
for (let channel = 0; channel < 2; channel++) { const data = buffer.getChannelData(channel); for (let i = 0; i < length; i++) data[i] = (r() * 2 - 1) * Math.exp(-i / length * 8) * .65; }
return buffer;
}
function trackBus(context, track, seed) {
const filter = context.createBiquadFilter(); filter.type = 'lowpass'; filter.frequency.value = track.tone; filter.Q.value = .45;
const volume = context.createGain(); volume.gain.value = track.gain;
const pan = context.createStereoPanner(); pan.pan.value = track.pan;
filter.connect(volume); volume.connect(pan); pan.connect(context.destination);
if (track.space > 0) {
const reverb = context.createConvolver(), send = context.createGain(); reverb.buffer = impulse(context, seed + ':room'); send.gain.value = track.space;
volume.connect(send); send.connect(reverb); reverb.connect(pan);
}
if (track.delay > 0) {
const delay = context.createDelay(2), feedback = context.createGain(), send = context.createGain();
delay.delayTime.value = .31; feedback.gain.value = .28; send.gain.value = track.delay;
volume.connect(send); send.connect(delay); delay.connect(feedback); feedback.connect(delay); delay.connect(pan);
}
return filter;
}
function envelope(context, target, time, duration, velocity, attack, release, sustained = false) {
const gain = context.createGain(), level = Math.max(.00001, velocity * .32), hold = Math.max(time + attack + .002, time + duration);
gain.gain.setValueAtTime(.00001, time);
gain.gain.exponentialRampToValueAtTime(level, time + attack);
if (sustained) gain.gain.linearRampToValueAtTime(level * .75, hold);
else gain.gain.exponentialRampToValueAtTime(Math.max(.00001, level * .24), hold);
gain.gain.exponentialRampToValueAtTime(.00001, hold + release);
gain.connect(target); return { gain, end: hold + release + .01 };
}
function synthNote(context, target, track, note, time, duration, seed, assets) {
const f = 440 * 2 ** ((note.midi - 69) / 12), kind = track.instrument, key = `${seed}:${note.beat}:${note.midi}`;
if (note.velocity <= 0) return;
if (kind === 'drums') {
const gain = context.createGain(); gain.connect(target);
if ([35, 36].includes(note.midi)) {
const osc = context.createOscillator(); osc.frequency.setValueAtTime(150, time); osc.frequency.exponentialRampToValueAtTime(44, time + .16);
gain.gain.setValueAtTime(.00001, time); gain.gain.exponentialRampToValueAtTime(note.velocity * .8, time + .003); gain.gain.exponentialRampToValueAtTime(.00001, time + .36);
osc.connect(gain); osc.start(time); osc.stop(time + .37);
} else {
const hat = [42, 44, 46, 49, 51].includes(note.midi), length = note.midi === 46 ? .36 : hat ? .10 : .23;
const source = context.createBufferSource(), filter = context.createBiquadFilter();
source.buffer = noiseBuffer(context, key, length); filter.type = hat ? 'highpass' : 'bandpass'; filter.frequency.value = hat ? 7000 : 1700; filter.Q.value = hat ? .4 : .8;
source.connect(filter); filter.connect(gain);
gain.gain.setValueAtTime(Math.max(.00001, note.velocity * (hat ? .23 : .63)), time); gain.gain.exponentialRampToValueAtTime(.00001, time + length);
source.start(time); source.stop(time + length);
if (!hat) { const body = context.createOscillator(); body.type = 'triangle'; body.frequency.value = 185; const bodyGain = context.createGain(); bodyGain.gain.setValueAtTime(note.velocity * .13, time); bodyGain.gain.exponentialRampToValueAtTime(.00001, time + .14); body.connect(bodyGain); bodyGain.connect(target); body.start(time); body.stop(time + .15); }
}
return;
}
const env = envelope(context, target, time, duration, note.velocity, kind === 'pad' ? Math.max(.12, track.attack) : track.attack, track.release, kind === 'pad' || kind === 'lead');
if (kind === 'sampler') {
const source = context.createBufferSource(); source.buffer = assets.get(track.sampleId); source.playbackRate.value = 2 ** ((note.midi - track.sampleRoot) / 12); source.connect(env.gain); source.start(time); source.stop(env.end); return;
}
if (kind === 'pluck') {
const length = Math.ceil((duration + track.release + .02) * context.sampleRate), buffer = context.createBuffer(1, length, context.sampleRate), out = buffer.getChannelData(0);
const size = Math.max(2, Math.round(context.sampleRate / f)), line = new Float32Array(size), r = musicRandom(key);
for (let i = 0; i < size; i++) line[i] = r() * 2 - 1;
for (let i = 0; i < length; i++) { const pos = i % size, next = (pos + 1) % size; out[i] = line[pos]; line[pos] = (line[pos] + line[next]) * .4988; }
const source = context.createBufferSource(); source.buffer = buffer; source.connect(env.gain); source.start(time); source.stop(env.end); return;
}
const osc = context.createOscillator(); osc.frequency.value = f;
if (kind === 'felt' || kind === 'bell') {
const harmonics = kind === 'felt' ? [0, 1, .25, .1, .04, .008] : [0, 1, .01, .38, .04, .16, .04];
osc.setPeriodicWave(context.createPeriodicWave(new Float32Array(harmonics.length), new Float32Array(harmonics)));
} else osc.type = kind === 'pad' ? 'sawtooth' : kind === 'bass' ? 'triangle' : 'sine';
osc.connect(env.gain); osc.start(time); osc.stop(env.end);
if (kind === 'pad' || kind === 'bass') {
const second = context.createOscillator(), mix = context.createGain(); second.type = 'sine'; second.frequency.value = kind === 'bass' ? f / 2 : f; second.detune.value = kind === 'pad' ? 7 : 0; mix.gain.value = .32; second.connect(mix); mix.connect(env.gain); second.start(time); second.stop(env.end);
}
}
async function renderSession(project, { onlyTrack, sampleRate = 48000 } = {}) {
const duration = secondsAt(project, project.beats) + (project.tail ?? 1.5), context = new OfflineAudioContext(2, Math.ceil(duration * sampleRate), sampleRate);
const assets = await audioAssets(project, context);
const tracks = onlyTrack ? project.tracks.filter(t => t.id === onlyTrack) : activeTracks(project);
for (const track of tracks) {
const seed = project.seed + ':' + track.id, bus = trackBus(context, track, seed);
for (const note of track.notes) {
const time = secondsAt(project, note.beat), length = secondsAt(project, note.beat + note.duration) - time;
synthNote(context, bus, track, note, time, length, seed, assets);
}
for (const clip of track.clips) {
const buffer = assets.get(clip.assetId), start = secondsAt(project, clip.beat);
if (clip.offset + clip.duration > buffer.duration + .03) throw new Error(`${track.name}: the clip extends beyond its recording.`);
const source = context.createBufferSource(), gain = context.createGain(); source.buffer = buffer;
const fadeIn = Math.min(clip.fadeIn, clip.duration / 2), fadeOut = Math.min(clip.fadeOut, clip.duration / 2), level = clip.gain;
gain.gain.setValueAtTime(fadeIn ? 0 : level, start); if (fadeIn) gain.gain.linearRampToValueAtTime(level, start + fadeIn);
gain.gain.setValueAtTime(level, start + clip.duration - fadeOut); if (fadeOut) gain.gain.linearRampToValueAtTime(0, start + clip.duration);
source.connect(gain); gain.connect(bus); source.start(start, clip.offset, clip.duration);
}
}
const buffer = await context.startRendering(), channels = [buffer.getChannelData(0), buffer.getChannelData(1)];
let peak = 0, energy = 0;
for (const data of channels) for (let i = 0; i < data.length; i++) {
// The same linear ending fade is applied to each stem and the mix.
data[i] *= Math.min(1, (data.length - 1 - i) / (sampleRate * .015));
peak = Math.max(peak, Math.abs(data[i])); energy += data[i] ** 2;
}
const gain = project.master * Math.min(1, .95 / Math.max(peak, .000001));
return { buffer, channels, sampleRate, duration: buffer.duration, rawPeak: peak, gain, peak: peak * gain, rms: Math.sqrt(energy / (buffer.length * 2)) * gain };
}
</script><script>function filename(name) { return String(name).normalize('NFKD').replace(/[^a-zA-Z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 100) || 'artwork'; }
// ZIP STORE: portable editable delivery without a runtime dependency or a cloud service.
function zipFiles(files) {
const enc = new TextEncoder(), chunks = [], central = []; let offset = 0;
for (const [name, body] of files) {
const path = enc.encode(name), bytes = typeof body === 'string' ? enc.encode(body) : new Uint8Array(body);
let crc = 0xffffffff;
for (const b of bytes) { crc ^= b; for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); }
crc = (crc ^ 0xffffffff) >>> 0;
const header = new Uint8Array(30 + path.length), v = new DataView(header.buffer);
v.setUint32(0, 0x04034b50, true); v.setUint16(4, 20, true); v.setUint16(6, 0x800, true); v.setUint16(12, 33, true);
v.setUint32(14, crc, true); v.setUint32(18, bytes.length, true); v.setUint32(22, bytes.length, true); v.setUint16(26, path.length, true); header.set(path, 30);
const row = new Uint8Array(46 + path.length), c = new DataView(row.buffer);
c.setUint32(0, 0x02014b50, true); c.setUint16(4, 20, true); c.setUint16(6, 20, true); c.setUint16(8, 0x800, true); c.setUint16(14, 33, true);
c.setUint32(16, crc, true); c.setUint32(20, bytes.length, true); c.setUint32(24, bytes.length, true); c.setUint16(28, path.length, true); c.setUint32(42, offset, true); row.set(path, 46);
chunks.push(header, bytes); central.push(row); offset += header.length + bytes.length;
}
const length = central.reduce((n, row) => n + row.length, 0), end = new Uint8Array(22), e = new DataView(end.buffer);
e.setUint32(0, 0x06054b50, true); e.setUint16(8, files.length, true); e.setUint16(10, files.length, true); e.setUint32(12, length, true); e.setUint32(16, offset, true);
return new Blob([...chunks, ...central, end], { type: 'application/zip' });
}
</script><script>const $ = selector => document.querySelector(selector), colors = ['#eabe90', '#b9acf1', '#8bc9ba', '#98bce8', '#dc9caa', '#cad990'];
const original = validateSession(JSON.parse($('#afterhours-data').textContent)), storageKey = 'afterhours:' + original.id;
let project = structuredClone(original), selectedTrack = 0, selectedNote = -1, selectedClip = 0, windowBar = 0, undoStack = [], redoStack = [], pendingDraft, preserveDraft = false;
let mix, mixRevision = -1, revision = 0, renderPromise, renderTimer, playback, audioContext, startedAt = 0, seekSeconds = 0, toastTimer, noteRects = [], pianoBounds;
const state = () => ({ project: structuredClone(project), selectedTrack, windowBar });
const track = () => project.tracks[selectedTrack];
const duration = () => secondsAt(project, project.beats) + (project.tail ?? 1.5);
const clock = value => { const seconds = Math.floor(Math.max(0, value) + .001); return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; };
function toast(message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 6000); }
function parentMessage(type, extra = {}) { if (parent !== window) parent.postMessage({ type, ...extra }, '*'); }
function persist() {
if (preserveDraft) return;
try { localStorage.setItem(storageKey, JSON.stringify({ baseRevision: original.revision, ...state() })); $('#draft-status').textContent = 'Draft saved on this device'; }
catch { $('#draft-status').textContent = 'Save project to keep your recordings'; }
}
function stop() { if (playback) { playback.onended = null; playback.stop(); playback.disconnect(); playback = null; } $('#play').textContent = '▶ Play'; $('#play').setAttribute('aria-label', 'Play'); }
function change(mutate, { rebuild = true } = {}) {
const previous = state();
try { mutate(); project = validateSession(project); }
catch (error) { project = previous.project; selectedTrack = previous.selectedTrack; toast(error.message); buildUI(); return; }
undoStack.push(previous); if (undoStack.length > 16) undoStack.shift(); redoStack = [];
stop(); revision++; mixRevision = -1; selectedNote = Math.min(selectedNote, track().notes.length - 1);
if (rebuild) buildUI(); else updateLabels(); persist(); scheduleMix();
}
function restore(saved) { stop(); project = validateSession(saved.project); selectedTrack = Math.min(saved.selectedTrack || 0, project.tracks.length - 1); windowBar = saved.windowBar || 0; selectedNote = -1; revision++; mixRevision = -1; buildUI(); persist(); scheduleMix(); }
function saveFile(name, content, type = 'application/octet-stream') { const blob = content instanceof Blob ? content : new Blob([content], { type }), url = URL.createObjectURL(blob), a = document.createElement('a'); a.href = url; a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(url), 30000); }
function canvasContext(canvas) {
const box = canvas.getBoundingClientRect(), ratio = Math.min(devicePixelRatio || 1, 2), w = Math.max(1, Math.round(box.width)), h = Math.max(1, Math.round(box.height));
if (canvas.width !== Math.round(w * ratio) || canvas.height !== Math.round(h * ratio)) { canvas.width = Math.round(w * ratio); canvas.height = Math.round(h * ratio); }
const ctx = canvas.getContext('2d'); ctx.setTransform(ratio, 0, 0, ratio, 0, 0); ctx.clearRect(0, 0, w, h); return { ctx, w, h };
}
function updateLabels() {
$('#title').textContent = project.title; document.title = project.title + ' · Afterhours'; $('#brief').textContent = project.brief;
$('#tempo').value = Number(project.tempo.toFixed(3)); $('#bars').value = Math.ceil(project.beats / beatsPerBar(project)); $('#meter').textContent = project.meter.join(' / ');
$('#gain-label').value = `${Math.round(track().gain * 100)}%`; $('#pan-label').value = track().pan === 0 ? 'Center' : `${Math.round(Math.abs(track().pan) * 100)}% ${track().pan < 0 ? 'left' : 'right'}`;
$('#undo').disabled = !undoStack.length; $('#redo').disabled = !redoStack.length;
$('#mute').setAttribute('aria-pressed', track().muted); $('#solo').setAttribute('aria-pressed', track().solo);
}
function buildUI() {
selectedTrack = Math.min(selectedTrack, project.tracks.length - 1);
windowBar = Math.max(0, Math.min(windowBar, Math.max(0, Math.ceil(project.beats / beatsPerBar(project)) - 1)));
updateLabels();
$('#tracks').replaceChildren(); $('#sections').replaceChildren();
project.sections.forEach((s, i) => { const div = document.createElement('div'); div.className = 'section'; div.textContent = s.name; div.style.left = `${s.beat / project.beats * 100}%`; div.style.width = `${s.length / project.beats * 100}%`; div.style.color = colors[i % colors.length]; $('#sections').append(div); });
project.tracks.forEach((t, i) => {
const row = document.createElement('div'), info = document.createElement('div'), name = document.createElement('button'), mute = document.createElement('button'), solo = document.createElement('button'), canvas = document.createElement('canvas');
row.className = 'track' + (selectedTrack === i ? ' selected' : ''); info.className = 'track-info'; name.className = 'track-name'; name.textContent = t.name; name.title = t.name; name.style.color = colors[i % colors.length];
name.onclick = () => { selectedTrack = i; selectedNote = -1; selectedClip = 0; buildUI(); };
mute.className = solo.className = 'mini'; mute.textContent = 'M'; solo.textContent = 'S'; mute.setAttribute('aria-label', `Mute ${t.name}`); solo.setAttribute('aria-label', `Solo ${t.name}`); mute.setAttribute('aria-pressed', t.muted); solo.setAttribute('aria-pressed', t.solo);
mute.onclick = () => change(() => { t.muted = !t.muted; }); solo.onclick = () => change(() => { t.solo = !t.solo; });
canvas.dataset.track = i; canvas.setAttribute('aria-label', t.name + ' arrangement'); canvas.onclick = event => { selectedTrack = i; selectedNote = -1; const box = canvas.getBoundingClientRect(); seekSeconds = secondsAt(project, Math.max(0, Math.min(project.beats, (event.clientX - box.left) / box.width * project.beats))); stop(); buildUI(); };
info.append(name, mute, solo); row.append(info, canvas); $('#tracks').append(row);
});
$('#track-name').value = track().name;
$('#instrument').replaceChildren();
for (const [key, label] of Object.entries(instruments)) { if (key === 'sampler' && !project.assets.length || key === 'audio' && track().instrument !== 'audio') continue; const option = document.createElement('option'); option.value = key; option.textContent = label; $('#instrument').append(option); }
$('#instrument').value = track().instrument;
for (const name of ['gain', 'pan', 'attack', 'release', 'tone', 'space', 'delay']) $('#' + name).value = track()[name];
$('#master').value = project.master; $('#sampler-controls').hidden = track().instrument !== 'sampler'; $('#sample-id').replaceChildren();
for (const asset of project.assets) { const option = document.createElement('option'); option.value = asset.id; option.textContent = asset.name; $('#sample-id').append(option); }
$('#sample-id').value = track().sampleId || project.assets[0]?.id || ''; $('#sample-root').value = noteName(track().sampleRoot);
$('#clip-controls').hidden = !track().clips.length;
selectedClip = Math.max(0, Math.min(selectedClip, track().clips.length - 1)); $('#clip-select').replaceChildren();
track().clips.forEach((c, i) => { const option = document.createElement('option'); option.value = i; option.textContent = `${i + 1}. ${project.assets.find(a => a.id === c.assetId)?.name || 'Recording'} · beat ${c.beat}`; $('#clip-select').append(option); });
$('#clip-select').value = selectedClip;
if (track().clips[selectedClip]) for (const [id, key] of [['clip-beat', 'beat'], ['clip-offset', 'offset'], ['clip-duration', 'duration']]) $('#' + id).value = track().clips[selectedClip][key];
$('#remove-track').disabled = project.tracks.length === 1;
updateNote(); requestAnimationFrame(drawAll);
}
function drawArrangement() {
const beat = beatAt(project, playback ? Math.max(0, audioContext.currentTime - startedAt) : seekSeconds);
for (const canvas of document.querySelectorAll('#tracks canvas')) {
const i = Number(canvas.dataset.track), t = project.tracks[i], { ctx, w, h } = canvasContext(canvas), unit = w / project.beats;
ctx.strokeStyle = '#ffffff09'; ctx.lineWidth = 1;
for (let b = 0; b <= project.beats; b += beatsPerBar(project)) { ctx.beginPath(); ctx.moveTo(b * unit + .5, 0); ctx.lineTo(b * unit + .5, h); ctx.stroke(); }
ctx.fillStyle = colors[i % colors.length]; ctx.globalAlpha = t.muted ? .18 : .75;
for (const n of t.notes) ctx.fillRect(n.beat * unit, 6 + (1 - (n.midi % 36) / 36) * (h - 15), Math.max(2, n.duration * unit - 1), 3);
for (const clip of t.clips) { const x = clip.beat * unit, width = (beatAt(project, secondsAt(project, clip.beat) + clip.duration) - clip.beat) * unit; ctx.globalAlpha = .24; ctx.fillRect(x, 6, width, h - 12); ctx.globalAlpha = .85; ctx.font = '9px sans-serif'; ctx.save(); ctx.beginPath(); ctx.rect(x + 4, 4, Math.max(0, width - 8), h - 8); ctx.clip(); ctx.fillText(project.assets.find(a => a.id === clip.assetId)?.name || 'Recording', x + 6, h / 2 + 3); ctx.restore(); }
ctx.globalAlpha = 1; ctx.fillStyle = '#f8e5ca'; ctx.fillRect(Math.min(w - 1, beat * unit), 0, 1, h);
}
}
function drawPiano() {
const { ctx, w, h } = canvasContext($('#piano')), bar = beatsPerBar(project), start = windowBar * bar, span = Math.min(8 * bar, project.beats - start), labelWidth = 37;
const notes = track().notes, lowest = Math.min(...notes.map(n => n.midi), 60), highest = Math.max(...notes.map(n => n.midi), 72);
const low = Math.max(0, Math.floor(lowest / 12) * 12 - 3), high = Math.min(127, Math.max(low + 24, highest + 4)), rows = high - low + 1, rowHeight = (h - 24) / rows, unit = (w - labelWidth) / Math.max(span, 1);
pianoBounds = { w, h, low, high, rows, rowHeight, unit, start, span, labelWidth }; noteRects = [];
for (let midi = low; midi <= high; midi++) {
const y = 24 + (high - midi) * rowHeight; ctx.fillStyle = [1, 3, 6, 8, 10].includes(midi % 12) ? '#ffffff02' : '#ffffff06'; ctx.fillRect(labelWidth, y, w - labelWidth, rowHeight - .5);
if (midi % 12 === 0) { ctx.fillStyle = '#737d94'; ctx.font = '9px monospace'; ctx.fillText(noteName(midi), 5, y + rowHeight); }
}
for (let beat = 0; beat <= span; beat += 4 / project.meter[1]) { const x = labelWidth + beat * unit, major = Math.abs(beat / bar - Math.round(beat / bar)) < .0001; ctx.strokeStyle = major ? '#ffffff24' : '#ffffff09'; ctx.beginPath(); ctx.moveTo(x + .5, 24); ctx.lineTo(x + .5, h); ctx.stroke(); if (major) { ctx.fillStyle = '#838da2'; ctx.font = '9px monospace'; ctx.fillText(String(Math.round((start + beat) / bar) + 1), x + 4, 15); } }
notes.forEach((n, i) => {
if (n.beat + n.duration <= start || n.beat >= start + span) return;
const x = labelWidth + Math.max(0, n.beat - start) * unit, y = 24 + (high - n.midi) * rowHeight + 1, width = Math.max(3, (Math.min(start + span, n.beat + n.duration) - Math.max(start, n.beat)) * unit - 1);
ctx.globalAlpha = .4 + n.velocity * .6; ctx.fillStyle = i === selectedNote ? '#fff4df' : colors[selectedTrack % colors.length]; ctx.fillRect(x, y, width, Math.max(2, rowHeight - 2)); ctx.globalAlpha = 1;
noteRects.push({ index: i, x, y, width, height: Math.max(3, rowHeight) });
});
$('#bar-window').textContent = `${windowBar + 1}–${Math.ceil((start + span) / bar)}`; $('#previous-bars').disabled = windowBar === 0; $('#next-bars').disabled = start + span >= project.beats;
$('#piano-title').textContent = track().name + (track().instrument === 'audio' ? ' · recording' : ' · notes');
}
function drawWave() {
const { ctx, w, h } = canvasContext($('#waveform'));
if (mix) {
for (let channel = 0; channel < 2; channel++) {
const samples = mix.channels[channel], stride = Math.max(1, Math.floor(samples.length / w)), center = h * (channel ? .75 : .25);
ctx.strokeStyle = channel ? '#b9acf1' : '#eabe90'; ctx.lineWidth = 1;
ctx.beginPath();
for (let x = 0; x < w; x++) { let peak = 0; for (let j = x * stride; j < Math.min(samples.length, (x + 1) * stride); j += Math.max(1, Math.floor(stride / 24))) peak = Math.max(peak, Math.abs(samples[j])); const length = peak * mix.gain * h * .24; ctx.moveTo(x, center - Math.max(.5, length)); ctx.lineTo(x, center + Math.max(.5, length)); }
ctx.stroke();
}
}
const current = playback ? Math.min(duration(), Math.max(0, audioContext.currentTime - startedAt)) : Math.min(duration(), seekSeconds);
ctx.fillStyle = '#ffffffb3'; ctx.fillRect(current / duration() * w, 0, 1, h); $('#time').textContent = clock(current) + ' / ' + clock(duration());
}
function drawAll() { drawArrangement(); drawPiano(); drawWave(); }
function updateNote() {
const n = track().notes[selectedNote];
for (const id of ['note-pitch', 'note-start', 'note-velocity']) $('#' + id).disabled = !n;
$('#delete-note').disabled = !n;
if (n) { $('#note-pitch').value = noteName(n.midi); $('#note-start').value = Number(n.beat.toFixed(4)); $('#note-length').value = Number(n.duration.toFixed(4)); $('#note-velocity').value = n.velocity; }
}
async function ensureMix() {
if (mixRevision === revision && mix) return mix;
if (renderPromise?.revision === revision) return renderPromise.promise;
const current = revision, candidate = structuredClone(project);
$('#audio-status').textContent = 'Rendering your arrangement…'; $('#error').hidden = true;
$('#play').disabled = $('#export-wav').disabled = $('#export-stems').disabled = true;
const promise = renderSession(candidate).then(result => {
if (current !== revision) return result;
mix = result; mixRevision = current;
$('#audio-status').textContent = activeTracks(project).length + ' tracks · ready to play';
$('#level').textContent = `PEAK ${result.peak > 0 ? (20 * Math.log10(result.peak)).toFixed(1) : '−∞'} dBFS / 48 kHz`;
$('#play').disabled = $('#export-wav').disabled = $('#export-stems').disabled = false;
document.body.dataset.ready = 'true'; parentMessage('harness:ready'); drawWave(); return result;
}).catch(error => {
if (current === revision) { $('#error').textContent = error.message; $('#error').hidden = false; $('#audio-status').textContent = 'A track needs attention'; parentMessage('harness:error', { message: error.message }); }
throw error;
});
renderPromise = { revision: current, promise }; return promise;
}
function scheduleMix() { $('#play').disabled = $('#export-wav').disabled = $('#export-stems').disabled = true; clearTimeout(renderTimer); renderTimer = setTimeout(() => ensureMix().catch(() => {}), 240); }
function guard(task) { return async (...args) => { try { await task(...args); } catch (error) { toast(error.message || String(error)); } }; }
async function play() {
if (playback) { seekSeconds = audioContext.currentTime - startedAt; stop(); return; }
const current = revision, rendered = await ensureMix(); if (current !== revision) return;
audioContext ??= new AudioContext(); await audioContext.resume();
const source = audioContext.createBufferSource(), gain = audioContext.createGain(); source.buffer = rendered.buffer; gain.gain.value = rendered.gain; source.connect(gain); gain.connect(audioContext.destination);
if (seekSeconds >= rendered.duration - .05) seekSeconds = 0;
startedAt = audioContext.currentTime - seekSeconds; source.start(0, seekSeconds); playback = source;
$('#play').textContent = 'Ⅱ Pause'; $('#play').setAttribute('aria-label', 'Pause');
source.onended = () => { if (playback === source) { playback = null; seekSeconds = 0; $('#play').textContent = '▶ Play'; $('#play').setAttribute('aria-label', 'Play'); } };
}
$('#play').onclick = guard(play); $('#stop').onclick = () => { stop(); seekSeconds = 0; drawAll(); };
$('#waveform').onclick = guard(async event => { const wasPlaying = !!playback, box = $('#waveform').getBoundingClientRect(); stop(); seekSeconds = Math.max(0, Math.min(duration() - .02, (event.clientX - box.left) / box.width * duration())); if (wasPlaying) await play(); drawAll(); });
let drag;
$('#piano').onpointerdown = event => {
if (!event.isPrimary || event.button !== 0) return;
if (track().instrument === 'audio') { toast('Use the recording controls to move or trim this clip.'); return; }
const box = $('#piano').getBoundingClientRect(), x = event.clientX - box.left, y = event.clientY - box.top, hit = noteRects.find(r => x >= r.x && x <= r.x + r.width && y >= r.y && y <= r.y + r.height);
if (hit) {
selectedNote = hit.index; drag = { x, y, previous: state(), note: { ...track().notes[selectedNote] }, moved: false }; $('#piano').setPointerCapture(event.pointerId); updateNote(); drawPiano();
} else if (x > pianoBounds.labelWidth && y > 24) {
const beat = Math.round((pianoBounds.start + (x - pianoBounds.labelWidth) / pianoBounds.unit) * 4) / 4, midi = Math.max(0, Math.min(127, pianoBounds.high - Math.floor((y - 24) / pianoBounds.rowHeight))), length = Math.max(.125, Number($('#note-length').value) || 1);
if (beat >= project.beats) return;
change(() => { track().notes.push({ beat, midi, duration: Math.min(length, project.beats - beat), velocity: Number($('#note-velocity').value) || .75 }); selectedNote = track().notes.length - 1; });
}
};
$('#piano').onpointermove = event => {
if (!drag) return;
const box = $('#piano').getBoundingClientRect(), dx = event.clientX - box.left - drag.x, dy = event.clientY - box.top - drag.y;
if (!drag.moved && Math.abs(dx) + Math.abs(dy) < 4) return;
drag.moved = true; stop(); const n = track().notes[selectedNote];
n.beat = Math.max(0, Math.min(project.beats - n.duration, Math.round((drag.note.beat + dx / pianoBounds.unit) * 4) / 4));
n.midi = Math.max(0, Math.min(127, drag.note.midi - Math.round(dy / pianoBounds.rowHeight))); updateNote(); drawPiano(); drawArrangement();
};
function endDrag() { if (drag?.moved) { undoStack.push(drag.previous); if (undoStack.length > 16) undoStack.shift(); redoStack = []; revision++; mixRevision = -1; persist(); scheduleMix(); updateLabels(); } drag = null; }
$('#piano').onpointerup = endDrag; $('#piano').onpointercancel = endDrag;
for (const [id, key, parse] of [['note-pitch', 'midi', noteNumber], ['note-start', 'beat', Number], ['note-length', 'duration', Number], ['note-velocity', 'velocity', Number]]) $('#' + id).onchange = () => { if (selectedNote < 0) return; change(() => { track().notes[selectedNote][key] = parse($('#' + id).value); }); };
$('#delete-note').onclick = () => { if (selectedNote >= 0) change(() => { track().notes.splice(selectedNote, 1); selectedNote = -1; }); };
$('#previous-bars').onclick = () => { windowBar = Math.max(0, windowBar - 8); drawPiano(); }; $('#next-bars').onclick = () => { windowBar += 8; drawPiano(); };
$('#duplicate-section').onclick = () => change(() => { const start = windowBar * beatsPerBar(project), length = Math.min(8 * beatsPerBar(project), project.beats - start); project = duplicateSection(project, start, length); windowBar = Math.floor((project.beats - length) / beatsPerBar(project)); });
$('#track-name').onchange = () => change(() => { track().name = $('#track-name').value.trim() || 'Instrument'; });
$('#instrument').onchange = () => change(() => { track().instrument = $('#instrument').value; delete track().midiProgram; if (track().instrument === 'sampler') track().sampleId = project.assets[0]?.id; });
for (const key of ['gain', 'pan', 'attack', 'release', 'tone', 'space', 'delay']) $('#' + key).onchange = () => change(() => { track()[key] = Number($('#' + key).value); });
$('#mute').onclick = () => change(() => { track().muted = !track().muted; }); $('#solo').onclick = () => change(() => { track().solo = !track().solo; });
$('#master').onchange = () => change(() => { project.master = Number($('#master').value); });
$('#tempo').onchange = () => change(() => { const ratio = Number($('#tempo').value) / project.tempo; project.tempos.forEach(t => { t.bpm *= ratio; }); project.tempo = project.tempos[0].bpm; });
$('#bars').onchange = () => change(() => { const beats = Number($('#bars').value) * beatsPerBar(project); if (project.tracks.some(t => t.notes.some(n => n.beat + n.duration > beats) || t.clips.some(c => secondsAt(project, c.beat) + c.duration > secondsAt(project, beats)))) throw new Error('Move or shorten the ending notes and recordings before reducing the arrangement.'); project.beats = beats; project.sections = project.sections.filter(s => s.beat < beats).map(s => ({ ...s, length: Math.min(s.length, beats - s.beat) })); project.tempos = project.tempos.filter(t => t.beat < beats); });
$('#sample-id').onchange = () => change(() => { track().sampleId = $('#sample-id').value; }); $('#sample-root').onchange = () => change(() => { track().sampleRoot = noteNumber($('#sample-root').value); });
$('#clip-select').onchange = () => { selectedClip = Number($('#clip-select').value); buildUI(); };
for (const [id, key] of [['clip-beat', 'beat'], ['clip-offset', 'offset'], ['clip-duration', 'duration']]) $('#' + id).onchange = () => change(() => { const clip = track().clips[selectedClip]; clip[key] = Number($('#' + id).value); const end = beatAt(project, secondsAt(project, clip.beat) + clip.duration); project.beats = Math.max(project.beats, Math.ceil(end / beatsPerBar(project)) * beatsPerBar(project)); });
for (const [id, delta] of [['transpose-down', -12], ['transpose-up', 12]]) $('#' + id).onclick = () => change(() => { track().notes.forEach(n => { n.midi += delta; }); });
$('#add-track').onclick = () => change(() => { project.tracks.push({ id: 'instrument-' + Date.now(), name: 'Your instrument', instrument: 'felt', notes: [], clips: [] }); selectedTrack = project.tracks.length - 1; selectedNote = -1; });
$('#remove-track').onclick = () => { if (project.tracks.length > 1) change(() => { project.tracks.splice(selectedTrack, 1); selectedTrack = Math.min(selectedTrack, project.tracks.length - 1); selectedNote = -1; }); };
$('#undo').onclick = () => { if (undoStack.length) { redoStack.push(state()); restore(undoStack.pop()); } }; $('#redo').onclick = () => { if (redoStack.length) { undoStack.push(state()); restore(redoStack.pop()); } };
$('#reset-project').onclick = () => change(() => { project = structuredClone(original); selectedTrack = 0; selectedNote = -1; windowBar = 0; });
$('#save-project').onclick = () => saveFile(filename(project.title) + '.afterhours.json', JSON.stringify(project, null, 2), 'application/json');
$('#open-project').onclick = () => $('#project-file').click(); $('#open-midi').onclick = () => $('#midi-file').click(); $('#import-audio').onclick = () => $('#audio-file').click();
$('#project-file').onchange = guard(async () => { const file = $('#project-file').files[0]; if (!file) return; if (file.size > 28000000) throw new Error('Project exceeds 28 MB.'); const p = validateSession(JSON.parse(await file.text())); change(() => { project = p; selectedTrack = 0; selectedNote = -1; windowBar = 0; }); $('#project-file').value = ''; });
$('#midi-file').onchange = guard(async () => { const file = $('#midi-file').files[0]; if (!file) return; if (file.size > 4000000) throw new Error('MIDI file exceeds 4 MB.'); const p = readSessionMidi(new Uint8Array(await file.arrayBuffer()), Midi); change(() => { project = p; selectedTrack = 0; selectedNote = -1; windowBar = 0; }); $('#midi-file').value = ''; toast(p.importWarnings.length ? p.importWarnings[0] : 'Your notes and tempo changes are ready to arrange.'); });
$('#audio-file').onchange = guard(async () => {
const file = $('#audio-file').files[0]; if (!file) return; if (file.size > 18000000) throw new Error('Use a recording under 18 MB. A longer recording can be imported as MP3.');
const context = new OfflineAudioContext(1, 1, 48000), buffer = await context.decodeAudioData(await file.arrayBuffer());
if (buffer.duration > 240) throw new Error('Trim the recording to four minutes or less.');
const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(file); });
change(() => {
const id = 'recording-' + Date.now(); project.assets.push({ id, name: file.name, data });
project.beats = Math.max(project.beats, Math.ceil(beatAt(project, buffer.duration) / beatsPerBar(project)) * beatsPerBar(project));
project.tracks.push({ id, name: file.name.slice(0, 120), instrument: 'audio', gain: 1, tone: 20000, space: 0, notes: [], clips: [{ assetId: id, beat: 0, offset: 0, duration: buffer.duration, gain: 1, fadeIn: .02, fadeOut: .05 }] });
selectedTrack = project.tracks.length - 1; selectedNote = -1;
}); $('#audio-file').value = ''; toast('Your recording is in the arrangement. Move or trim it in the track controls.');
});
$('#export-wav').onclick = guard(async () => { const current = revision, result = await ensureMix(); if (current !== revision) throw new Error('The piece changed during export. Export the new version when it is ready.'); saveFile(filename(project.title) + '.wav', wavBytes(result.channels, result.sampleRate, result.gain), 'audio/wav'); });
$('#export-midi').onclick = guard(async () => { saveFile(filename(project.title) + '.mid', writeSessionMidi(project, Midi), 'audio/midi'); toast('Editable notes and tempo exported. Your recorded audio stays in the WAV stems and project.'); });
async function stemFiles() {
const candidate = structuredClone(project), result = await renderSession(candidate), audible = activeTracks(candidate);
if (audible.length * result.buffer.length * 4 > 512000000) throw new Error('This stem bundle exceeds 512 MB. Solo a smaller group of tracks and export in groups.');
const files = [['mix.wav', wavBytes(result.channels, result.sampleRate, result.gain)], ['composition.mid', writeSessionMidi(candidate, Midi)], ['project.afterhours.json', JSON.stringify(candidate, null, 2)]];
const report = { title: candidate.title, sampleRate: result.sampleRate, channels: 2, bitDepth: 16, duration: result.duration, commonGain: result.gain, peak: result.peak, stems: [] };
for (let i = 0; i < audible.length; i++) {
const t = audible[i], rendered = await renderSession(candidate, { onlyTrack: t.id }), name = `${String(i + 1).padStart(2, '0')}-${filename(t.name)}.wav`;
files.push(['stems/' + name, wavBytes(rendered.channels, rendered.sampleRate, result.gain)]); report.stems.push({ file: name, track: t.id, name: t.name });
}
files.push(['delivery.json', JSON.stringify(report, null, 2)], ['README.txt', `${candidate.title}\n\n${candidate.brief}\n\nDrag every WAV stem to time zero in your DAW. All stems share length, sample rate and mix gain. They contain the audible tracks at export time, including per-track effects. MIDI carries all notes and the tempo map, not recordings or audio effects. Synth previews need not sound like your DAW's MIDI instruments. project.afterhours.json preserves your notes, mix and embedded recordings.\n`]);
return { files, report };
}
$('#export-stems').onclick = guard(async () => { const name = filename(project.title); $('#export-stems').disabled = true; $('#audio-status').textContent = 'Rendering separate tracks…'; try { const { files, report } = await stemFiles(); saveFile(name + '-production.zip', zipFiles(files)); toast(`${report.stems.length} aligned WAV stems, mix, MIDI and editable project exported.`); } finally { $('#export-stems').disabled = false; $('#audio-status').textContent = 'Ready to play'; } });
$('#export-html').onclick = () => { const doc = document.documentElement.cloneNode(true); doc.querySelector('#afterhours-data').textContent = JSON.stringify(project).replace(/</g, '\\u003c'); doc.querySelector('#revision-notice').hidden = true; doc.querySelector('#error').hidden = true; doc.querySelector('#toast').className = ''; doc.querySelector('body').removeAttribute('data-ready'); saveFile(filename(project.title) + '-studio.html', '<!doctype html>\n' + doc.outerHTML, 'text/html'); };
$('#use-revision').onclick = () => { preserveDraft = false; $('#revision-notice').hidden = true; persist(); }; $('#keep-draft').onclick = () => { preserveDraft = false; $('#revision-notice').hidden = true; restore(pendingDraft); };
try { const saved = JSON.parse(localStorage.getItem(storageKey)); if (saved) { saved.project = validateSession(saved.project); if (saved.baseRevision === original.revision) { project = saved.project; selectedTrack = Math.min(saved.selectedTrack || 0, project.tracks.length - 1); windowBar = saved.windowBar || 0; } else { pendingDraft = saved; preserveDraft = true; $('#revision-notice').hidden = false; } } } catch {}
addEventListener('keydown', event => { if (event.target.closest('input,select,textarea')) return; if (event.code === 'Space') { event.preventDefault(); guard(play)(); } else if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'z') { event.preventDefault(); $('#' + (event.shiftKey ? 'redo' : 'undo')).click(); } else if (['Backspace', 'Delete'].includes(event.key) && event.target === $('#piano')) { event.preventDefault(); $('#delete-note').click(); } });
new ResizeObserver(drawAll).observe($('.main-panel'));
function animate() { if (playback) { drawWave(); drawArrangement(); } requestAnimationFrame(animate); }
window.afterhours = {
getProject: () => structuredClone(project), getState: () => ({ playing: !!playback, context: audioContext?.state, selectedTrack, selectedNote, peak: mix?.peak, rms: mix?.rms, duration: mix?.duration, revision, mixRevision }),
render: options => renderSession(project, options), midi: () => Array.from(writeSessionMidi(project, Midi)), stemFiles,
async deliver() { const result = await ensureMix(), bytes = new Blob([wavBytes(result.channels, result.sampleRate, result.gain)], { type: 'audio/wav' }); const wav = await new Promise(resolve => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.readAsDataURL(bytes); }); return { wav, duration: result.duration, peak: result.peak, rms: result.rms, sampleRate: result.sampleRate, gain: result.gain }; },
};
buildUI(); ensureMix().catch(() => {}); animate();
</script></body></html>