엘리제를 위하여, 장르 네 개
베토벤 「엘리제를 위하여」 멜로디를 Lo-fi·재즈·트랩·오케스트라로 바꿔 연주하는 페이지예요. 재생을 누르고 장르를 고르면 다음 마디부터 바뀌어요. 녹음이나 샘플 없이 브라우저가 소리를 직접 합성해요. 영상은 @ai.asap.kr 릴스에 있어요.

HTML 파일 한 개, 417줄.
광고
코드
Claude Code가 짠 코드 그대로예요. 릴스 소리는 같은 음표를 파이썬으로 합성한 판이라 음색이 조금 달라요.
광고
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>엘리제를 위하여 · 장르 네 개 · ASAP Lab</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=EB+Garamond:ital,wght@1,500&family=Nanum+Myeongjo:wght@800&display=swap" rel="stylesheet">
<!--
베토벤 「엘리제를 위하여」(1810, 저작권 만료) → Lo-fi · Jazz · Trap · Orchestra
녹음·샘플·사운드폰트 없이 브라우저 Web Audio 로 바로 합성한다. 이 파일 하나가 전부다.
릴스 소리는 같은 음표 목록을 파이썬(numpy)으로 합성한 판이라 음색이 조금 다르다.
ASAP · asapai.co.kr/lab
-->
<style>
:root { --blue:#4AAFFD; }
* { box-sizing:border-box; margin:0; padding:0; }
html, body { background:#000; color:#fff; height:100%; }
body { font-family:-apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Pretendard", sans-serif;
display:flex; flex-direction:column; align-items:center; min-height:100vh; padding:6vh 16px 4vh; }
h1 { font-family:"Nanum Myeongjo", serif; font-weight:800; font-size:clamp(34px, 7vw, 56px); letter-spacing:-.03em; text-align:center; }
.by { font-family:"EB Garamond", serif; font-style:italic; font-size:clamp(20px, 4vw, 30px); color:rgba(255,255,255,.75); margin-top:6px; }
#roll { width:min(720px, 100%); aspect-ratio:2.2/1; margin-top:4vh; display:block; }
#genre { font-family:"EB Garamond", serif; font-style:italic; font-size:clamp(40px, 9vw, 64px); height:1.2em; margin-top:1vh; transition:opacity .3s; }
#keys { width:min(720px, 100%); aspect-ratio:5.4/1; margin-top:2vh; display:block; }
.ctl { display:flex; flex-wrap:wrap; gap:10px; justify-content:center; margin-top:3vh; }
button { font:inherit; background:transparent; color:rgba(255,255,255,.6); border:1px solid rgba(255,255,255,.25);
padding:10px 18px; border-radius:999px; cursor:pointer; font-family:"EB Garamond", serif; font-style:italic; font-size:20px; }
button.on { color:#000; background:#fff; border-color:#fff; }
#play { font-family:inherit; font-style:normal; font-size:16px; font-weight:600; color:#000; background:var(--blue); border-color:var(--blue); padding:12px 26px; }
.note { margin-top:3vh; font-size:13px; color:rgba(255,255,255,.4); text-align:center; line-height:1.7; max-width:560px; }
#cursor, #logo { display:none; }
/* 녹화 모드(?rec): 릴스용 9:16 화면. 재생 버튼·안내 문구 없이, 커서가 장르를 누른다 */
body.rec { justify-content:flex-start; padding:118px 0 0; overflow:hidden; }
body.rec #play, body.rec .note, body.rec #playrow { display:none; }
body.rec h1 { font-size:42px; }
body.rec .by { font-size:25px; margin-top:4px; }
body.rec #roll { width:540px; margin-top:34px; }
body.rec #genre { font-size:44px; margin-top:4px; transition:none; }
body.rec #genres { margin-top:18px; gap:9px; }
body.rec #genres button { font-size:19px; padding:9px 17px; transition:none; }
body.rec #genres button.pend { border-color:#fff; color:#fff; }
body.rec #keys { width:480px; margin-top:34px; }
body.rec #logo { display:block; position:absolute; left:0; right:0; bottom:118px; margin:0 auto; width:76px; }
body.rec #cursor { display:block; position:absolute; left:0; top:0; pointer-events:none; z-index:9; will-change:transform; }
#cursor svg { position:absolute; left:0; top:0; filter:drop-shadow(0 1px 2px rgba(0,0,0,.45)); }
#cur-arrow { transform:translate(-3px,-2px); } #cur-hand { transform:translate(-12px,-3px); transform-origin:12px 3px; }
body.rec #genres button.hov:not(.on) { border-color:rgba(255,255,255,.6); color:rgba(255,255,255,.9); }
#ripple { position:absolute; left:0; top:0; width:44px; height:44px; margin:-22px 0 0 -22px; border-radius:50%; border:2px solid rgba(255,255,255,.9); opacity:0; pointer-events:none; z-index:8; }
</style>
</head>
<body>
<h1>엘리제를 위하여</h1>
<div class="by">by Claude Code</div>
<canvas id="roll"></canvas>
<div id="genre">Lo-fi</div>
<canvas id="keys"></canvas>
<div class="ctl" id="playrow">
<button id="play">재생</button>
</div>
<div class="ctl" id="genres">
<button data-g="lofi" class="on">Lo-fi</button>
<button data-g="jazz">Jazz</button>
<button data-g="trap">Trap</button>
<button data-g="orchestra">Orchestra</button>
</div>
<div id="cursor">
<svg id="cur-arrow" viewBox="0 0 26 26" width="26" height="26"><path d="M3 2 L3 21 L8 16.5 L11.5 24 L15 22.5 L11.6 15.2 L18 15.2 Z" fill="#000" stroke="#fff" stroke-width="1.6" stroke-linejoin="round"/></svg>
<svg id="cur-hand" viewBox="0 0 32 32" width="30" height="30"><path d="M12 3.5c1.1 0 2 .9 2 2V14l.9-.3c1-.3 2 .3 2.3 1.2l.2.5.6-.2c1-.3 2 .3 2.3 1.2l.2.6.4-.1c1-.2 2 .4 2.2 1.4l.8 4.4c.4 2.3-.4 4.6-2.1 6.1l-.6.5c-.7.6-1.6.9-2.5.9h-5.2c-1.3 0-2.5-.6-3.2-1.7l-4.3-6.3c-.6-.9-.4-2.1.5-2.7.8-.5 1.8-.4 2.5.3l1.1 1.2V5.5c0-1.1.9-2 2-2z" fill="#fff" stroke="#000" stroke-width="1.5" stroke-linejoin="round"/><path d="M14 14v5M17.4 15.4v4M20.5 17v3" stroke="#000" stroke-width="1.2" stroke-linecap="round"/></svg>
</div>
<div id="ripple"></div>
<img id="logo" alt="ASAP">
<p class="note">장르를 누르면 다음 마디부터 바뀌어요. 녹음·샘플 없이 이 페이지가 소리를 직접 합성해요.</p>
<script>
// ── 음표 ─────────────────────────────────────────────────────────────────
const NOTE = {C:0,"C#":1,D:2,"D#":3,E:4,F:5,"F#":6,G:7,"G#":8,A:9,"A#":10,B:11};
const midi = n => NOTE[n.slice(0,-1)] + 12 * (+n.slice(-1) + 1);
const hz = m => 440 * Math.pow(2, (m - 69) / 12);
// 원곡 3/8 한 마디(16분 6칸)를 4/4 반 마디(8칸)로 늘린 편곡 — 4마디(64칸)
const U1=[["E5",1],["D#5",1],["E5",1],["D#5",1],["E5",1],["B4",1],["D5",1],["C5",1]];
const U2=[["A4",2],["C4",1],["E4",1],["A4",4]], U3=[["B4",2],["E4",1],["G#4",1],["B4",4]];
const U4=[["C5",4],["E4",2],["E5",1],["D#5",1]], U5=[["B4",2],["E4",1],["C5",1],["B4",4]], U6=[["A4",6],["E5",1],["D#5",1]];
const MELODY=[...U1,...U2,...U3,...U4,...U1,...U2,...U5,...U6];
const MEL = {}; { let st=0; for (const [n,d] of MELODY) { MEL[st]=[midi(n), d]; st+=d; } }
// 반 마디마다 화음
const HALF = ["Am","Am","E","Am","Am","Am","E","Am"];
const ROOT = {Am:"A2", E:"E2"};
const LOFI_CH = [["Am9",["C4","E4","G4","B4"]],["Am9",["C4","E4","G4","B4"]],["E7",["D4","G#4","B4","F5"]],["Am9",["C4","E4","G4","B4"]],
["Fmaj7",["A3","C4","E4","G4"]],["Fmaj7",["A3","C4","E4","G4"]],["E7",["D4","G#4","B4","F5"]],["Am9",["C4","E4","G4","B4"]]];
const LOFI_ROOT = ["A2","A2","E2","A2","F2","F2","E2","A2"];
const JAZZ_V = {Am:["C4","E4","G4","B4"], E:["D4","G#4","B4","C5"]};
const WALK = {Am:["A2","C3","E3","G3"], E:["E2","G#2","B2","D3"]};
const PAD = {Am:["A3","C4","E4"], E:["G#3","B3","E4"]};
const ORCH = {Am:["A3","C4","E4","A4"], E:["G#3","B3","E4","B4"]};
const GENRES = { lofi:{name:"Lo-fi", bpm:78, swing:.17}, jazz:{name:"Jazz", bpm:100, swing:.30},
trap:{name:"Trap", bpm:74, swing:0}, orchestra:{name:"Orchestra", bpm:66, swing:0} };
// ── 사람 손 느낌(최소한): 칸마다 정해진 작은 흔들림 ─────────────────────────
function prng(seed){ return function(){ seed|=0; seed=seed+0x6D2B79F5|0; let t=Math.imul(seed^seed>>>15,1|seed); t=t+Math.imul(t^t>>>7,61|t)^t; return ((t^t>>>14)>>>0)/4294967296; }; }
const gauss = r => { const u=r()||1e-9, v=r(); return Math.sqrt(-2*Math.log(u))*Math.cos(2*Math.PI*v); };
const J = (st, salt, sd) => Math.max(-2.5*sd, Math.min(2.5*sd, gauss(prng(st*31+salt*7+12345)) * sd));
const HV = st => Math.max(.82, Math.min(1.18, 1 + gauss(prng(st*17+999)) * .08));
function DYN(pos){ const u=pos%8; let v=.86+.14*Math.sin(Math.PI*(u+.5)/8); if(pos%16===0) v+=.08; if(pos>=56) v*=.85; return v; }
// ── 오디오 ────────────────────────────────────────────────────────────────
let ac, master, verb, verbGain, tone, noiseBuf, nrand = prng(99);
function setup(ctx){
ac = ctx || new (window.AudioContext || window.webkitAudioContext)(); nrand = prng(99);
master = ac.createGain(); master.gain.value = .55;
const comp = ac.createDynamicsCompressor(); comp.threshold.value = -14; comp.ratio.value = 4;
tone = ac.createBiquadFilter(); tone.type = "lowpass"; tone.frequency.value = 20000;
verb = ac.createConvolver(); verbGain = ac.createGain(); verbGain.gain.value = .15;
const r = prng(7), len = ac.sampleRate * 2.2, ir = ac.createBuffer(2, len, ac.sampleRate);
for (let c=0;c<2;c++){ const d=ir.getChannelData(c); for(let i=0;i<len;i++) d[i]=(r()*2-1)*Math.pow(1-i/len, 3.2); }
verb.buffer = ir;
master.connect(tone); tone.connect(comp); master.connect(verb); verb.connect(verbGain); verbGain.connect(comp); comp.connect(ac.destination);
noiseBuf = ac.createBuffer(1, ac.sampleRate, ac.sampleRate);
const nd = noiseBuf.getChannelData(0), rn = prng(3); for (let i=0;i<nd.length;i++) nd[i]=rn()*2-1;
}
function env(g, t, a, peak, d, sus=0, end){
g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(peak, t+a);
g.gain.setTargetAtTime(peak*sus, t+a, d/3);
if (end) { g.gain.setTargetAtTime(0, end, .03); }
}
function osc(type, f, t, stop, dest){ const o=ac.createOscillator(); o.type=type; o.frequency.value=f; o.connect(dest); o.start(t); o.stop(stop); return o; }
function epiano(m, t, dur, vel){ // FM 일렉피아노
const f=hz(m), out=ac.createGain(); out.connect(master);
env(out, t, .004, vel*.5, 1.1, .1, t+dur);
const mod=ac.createGain(); mod.gain.setValueAtTime(f*1.8, t); mod.gain.setTargetAtTime(f*.25, t, .25);
const mo=osc("sine", f, t, t+dur+.3, mod); const car=osc("sine", f, t, t+dur+.3, out); mod.connect(car.frequency);
}
function piano(m, t, dur, vel){ // 배음 다섯 개가 따로 줄어드는 피아노
[[1,1],[2,.5],[3,.25],[4,.12],[5,.06]].forEach(([k,a])=>{
const g=ac.createGain(); g.connect(master); env(g, t, .003, vel*a*.32, 1.5/(1+k*.6), 0, t+dur+.3); osc("sine", hz(m)*k, t, t+dur+.8, g); });
}
function bell(m, t, dur, vel){
const f=hz(m)*2, out=ac.createGain(); out.connect(master); env(out, t, .002, vel*.4, .45, 0, t+dur+.2);
const mod=ac.createGain(); mod.gain.setValueAtTime(f*.8, t); mod.gain.setTargetAtTime(0, t, .15);
osc("sine", f*3.5, t, t+dur+.5, mod); const car=osc("sine", f, t, t+dur+.5, out); mod.connect(car.frequency);
}
function flute(m, t, dur, vel){
const out=ac.createGain(); out.connect(master); env(out, t, .04, vel*.35, 9, 1, t+dur);
const o=osc("sine", hz(m), t, t+dur+.2, out);
const lfo=ac.createOscillator(), lg=ac.createGain(); lfo.frequency.value=5.5; lg.gain.setValueAtTime(0,t); lg.gain.linearRampToValueAtTime(hz(m)*.006, t+.25);
lfo.connect(lg); lg.connect(o.frequency); lfo.start(t); lfo.stop(t+dur+.2);
}
function strings(m, t, dur, vel){
const out=ac.createGain(), lp=ac.createBiquadFilter(); lp.type="lowpass"; lp.frequency.value=2200;
out.connect(lp); lp.connect(master);
out.gain.setValueAtTime(0,t); out.gain.linearRampToValueAtTime(vel*.06, t+.35); out.gain.setTargetAtTime(0, t+dur, .15);
[-6,0,7].forEach(c=>{ const o=osc("sawtooth", hz(m), t, t+dur+.8, out); o.detune.value=c; });
}
function bass(m, t, dur, vel, wave="sine"){
const g=ac.createGain(); g.connect(master); env(g, t, .01, vel*.55, .6, .5, t+dur); osc(wave, hz(m), t, t+dur+.2, g);
}
function sub808(m, t, dur, vel){
const g=ac.createGain(), sh=ac.createWaveShaper(), curve=new Float32Array(256);
for (let i=0;i<256;i++){ const x=i/128-1; curve[i]=Math.tanh(2.2*x); } sh.curve=curve;
g.connect(sh); sh.connect(master); env(g, t, .003, vel*.7, .9, .2, t+dur);
const o=osc("sine", hz(m)*2, t, t+dur+.3, g); o.frequency.setTargetAtTime(hz(m), t, .03);
}
function noise(t, dur, vel, hp, lp, decay){
const s=ac.createBufferSource(); s.buffer=noiseBuf; const g=ac.createGain();
let node=s; if (hp){ const f=ac.createBiquadFilter(); f.type="highpass"; f.frequency.value=hp; node.connect(f); node=f; }
if (lp){ const f=ac.createBiquadFilter(); f.type="lowpass"; f.frequency.value=lp; node.connect(f); node=f; }
node.connect(g); g.connect(master); g.gain.setValueAtTime(vel, t); g.gain.setTargetAtTime(0, t, decay);
s.start(t, nrand()*.5); s.stop(t+dur);
}
function kick(t, vel=.9){ const g=ac.createGain(); g.connect(master); g.gain.setValueAtTime(vel, t); g.gain.setTargetAtTime(0, t, .12);
const o=osc("sine", 130, t, t+.5, g); o.frequency.setValueAtTime(130,t); o.frequency.setTargetAtTime(45, t, .035); }
function snare(t, vel=.45){ noise(t, .25, vel, 900, 5000, .05); const g=ac.createGain(); g.connect(master); g.gain.setValueAtTime(vel*.6,t); g.gain.setTargetAtTime(0,t,.04); osc("sine",185,t,t+.2,g); }
function hat(t, vel=.12, open=false){ noise(t, open?.2:.06, vel, 7000, 0, open?.06:.015); }
function timpani(m, t){ const g=ac.createGain(); g.connect(master); g.gain.setValueAtTime(.55,t); g.gain.setTargetAtTime(0,t,.45); osc("sine",hz(m),t,t+1.5,g); noise(t,.3,.2,0,400,.06); }
// ── 화면에 그릴 음 ─────────────────────────────────────────────────────────
const EV = [];
const push = (t, d, m, k) => { EV.push({t, d, m, k}); };
// ── 장르별 한 칸(16분) 연주 ─────────────────────────────────────────────────
function playStep(g, st, T, s16){
const sw = st%2 ? GENRES[g].swing*s16 : 0, at = (salt=0, sd=.004) => T + sw + J(st, salt, sd);
const pos = st % 16, h = Math.floor(st/8), ho = st % 8;
const mel = MEL[st];
if (mel){
const [m, d] = mel, t = at(7, .007), dur = d*s16, v = HV(st)*DYN(st);
if (g==="lofi") epiano(m, t, dur, .55*v);
if (g==="jazz") piano(m, t, dur, .55*v);
if (g==="trap") bell(m, t, dur, .45*v);
if (g==="orchestra") flute(m, t, dur, .55*v);
push(t, dur, m, "lead");
}
if (g==="lofi"){
if (ho===0){ LOFI_CH[h][1].forEach((n,k)=>{ const t=at()+k*(.008+Math.abs(J(st,3,.004))); epiano(midi(n), t, 8*s16, .2); push(t, 8*s16, midi(n), "chord"); });
bass(midi(LOFI_ROOT[h]), at(), 3*s16, .6); push(at(), 3*s16, midi(LOFI_ROOT[h]), "bass"); }
if (ho===6){ bass(midi(LOFI_ROOT[h]), at(), 2*s16, .45); push(at(), 2*s16, midi(LOFI_ROOT[h]), "bass"); }
if ([0,7,10].includes(pos)) { kick(at()); push(at(), .2, 0, "drum"); }
if ([4,12].includes(pos)) snare(at()+.006);
if ([3,9,11,15].includes(pos) && prng(st*100+pos)() < .35) snare(at(), .08);
if (pos%2===0) hat(at(), pos%4 ? .1 : .07, pos===14);
}
if (g==="jazz"){
const ch = HALF[h];
if ((h%2===0 && (ho===0 || ho===6)) || (h%2===1 && ho===4))
JAZZ_V[ch].forEach((n,k)=>{ const t=at()+.004+k*(.007+Math.abs(J(st,3,.004))); piano(midi(n), t, 3*s16, .16); push(t, 3*s16, midi(n), "chord"); });
if (ho===0 || ho===4){ const n = WALK[ch][((ho/4) + (h%2)*2) % 4]; bass(midi(n), at(), 4*s16, .7, "triangle"); push(at(), 4*s16, midi(n), "bass"); }
if ([0,4,7,8,12,15].includes(pos)) noise(at(), .35, .07, 5000, 0, .12);
if (pos===4 || pos===12) { noise(at(), .1, .05, 6000, 0, .03); push(at(), .2, 0, "drum"); }
if ([2,6,10,14].includes(pos) && prng(500+st*10)() < .4) noise(at(), .08, .03, 1500, 6000, .03);
}
if (g==="trap"){
const ch = HALF[h], bar = Math.floor(st/16);
if (ho===0){ PAD[ch].forEach(n=>strings(midi(n), at(), 8*s16, .7)); sub808(midi(ROOT[ch])-12, at(), 6*s16, .8); push(at(), 6*s16, midi(ROOT[ch]), "bass"); }
if (ho===6 && h%2===1) sub808(midi(ROOT[ch])-12+3, at(), 2*s16, .55);
if (pos===0 || pos===10) { kick(at()); push(at(), .2, 0, "drum"); }
if (pos===8) noise(at(), .25, .45, 1200, 7000, .06);
hat(at(), pos%2 ? .06 : .09);
if (bar%2===1 && pos>=13) hat(at()+s16/2, .07); // 마디 끝 하이햇 롤
else if (pos%2===0) hat(at()+s16/2, .05);
}
if (g==="orchestra"){
const ch = HALF[h];
if (ho===0){ ORCH[ch].forEach(n=>strings(midi(n), at(), 8*s16, 1)); strings(midi(ROOT[ch]), at(), 8*s16, 1.2); push(at(), 8*s16, midi(ROOT[ch]), "chord"); }
if (ho%2===0) bass(midi(ROOT[ch]) + (ho%4 ? 7 : 0), at(), .3, .35);
if (pos===0) { timpani(midi(st===16 ? "E2" : "A2"), at()); push(at(), 1, 0, "drum"); }
}
}
// ── 스케줄러: 미리 0.15초씩 예약 ───────────────────────────────────────────
let playing=false, genre="lofi", pending=null, step=0, nextT=0, timer=null;
function setGenreUI(g){
document.querySelectorAll("#genres button").forEach(b=>b.classList.toggle("on", b.dataset.g===g));
const el=document.getElementById("genre"); el.style.opacity=0; setTimeout(()=>{ el.textContent=GENRES[g].name; el.style.opacity=1; }, 200);
genreAudio(g, ac.currentTime);
}
function genreAudio(g, t){
tone.frequency.setTargetAtTime(g==="lofi" ? 3800 : 20000, t, .2);
verbGain.gain.setTargetAtTime(g==="orchestra" ? .35 : g==="jazz" ? .18 : .1, t, .3);
}
function tick(){
while (nextT < ac.currentTime + .15){
if (pending && step%16===0){ genre=pending; pending=null; setGenreUI(genre); }
const s16 = 60/GENRES[genre].bpm/4;
playStep(genre, step, nextT, s16);
nextT += s16; step = (step+1) % 64;
}
}
// 아이폰은 무음 스위치가 켜져 있으면 Web Audio 소리를 막는다 → 미디어 재생으로 알린다
// ① iOS 17+ : navigator.audioSession.type = "playback" ② 그 전 기기: 소리 없는 <audio> 를 반복 재생해 미디어 세션을 연다
let unmuteEl = null;
function silentWav(){ const n = 4410, b = new DataView(new ArrayBuffer(44 + n*2)); const w = (o, s) => [...s].forEach((c,i)=>b.setUint8(o+i, c.charCodeAt(0)));
w(0,"RIFF"); b.setUint32(4,36+n*2,true); w(8,"WAVEfmt "); b.setUint32(16,16,true); b.setUint16(20,1,true); b.setUint16(22,1,true);
b.setUint32(24,44100,true); b.setUint32(28,88200,true); b.setUint16(32,2,true); b.setUint16(34,16,true); w(36,"data"); b.setUint32(40,n*2,true);
let bin = ""; new Uint8Array(b.buffer).forEach(x => bin += String.fromCharCode(x)); return "data:audio/wav;base64," + btoa(bin); }
function unmuteIOS(){
try { if (navigator.audioSession) navigator.audioSession.type = "playback"; } catch(e) {}
if (!unmuteEl){ unmuteEl = document.createElement("audio"); unmuteEl.setAttribute("playsinline", ""); unmuteEl.loop = true; unmuteEl.src = silentWav(); }
unmuteEl.play().catch(() => {});
}
document.getElementById("play").onclick = async () => {
unmuteIOS(); // 반드시 누른 순간(사용자 동작 안)에 먼저
if (!ac) setup();
if (ac.state === "suspended" || ac.state === "interrupted") await ac.resume();
playing = !playing;
document.getElementById("play").textContent = playing ? "정지" : "재생";
if (playing){ step=0; nextT=ac.currentTime+.1; EV.length=0; setGenreUI(genre); timer=setInterval(tick, 25); }
else { clearInterval(timer); master.gain.setTargetAtTime(0, ac.currentTime, .05); setTimeout(()=>{ master.gain.value=.55; }, 400); if (unmuteEl) unmuteEl.pause(); }
};
document.querySelectorAll("#genres button").forEach(b => b.onclick = () => {
if (!playing || !ac){ genre=b.dataset.g; document.querySelectorAll("#genres button").forEach(x=>x.classList.toggle("on", x===b)); document.getElementById("genre").textContent=GENRES[genre].name; return; }
pending = b.dataset.g;
document.querySelectorAll("#genres button").forEach(x=>x.style.borderColor = x===b ? "#fff" : "");
});
// ── 그리기: 가운데 재생선 피아노 롤 + 건반 ─────────────────────────────────
const roll=document.getElementById("roll"), rc=roll.getContext("2d");
const keys=document.getElementById("keys"), kc=keys.getContext("2d");
function fit(cv){ const r=cv.getBoundingClientRect(), d=devicePixelRatio||1; cv.width=r.width*d; cv.height=r.height*d; return [r.width, r.height, d]; }
const MLO=39, MHI=77, KLO=48, KHI=84, WHITE=[0,2,4,5,7,9,11];
function draw(){ drawAt(ac && !REC ? ac.currentTime : (REC ? REC.t : 0)); if (!REC) requestAnimationFrame(draw); }
function drawAt(now){
const [W,H,d] = fit(roll); rc.setTransform(d,0,0,d,0,0); rc.clearRect(0,0,W,H);
const PX=W/2, PPS=W*0.2, y=m=>H*.08+(MHI-m)/(MHI-MLO)*H*.84, bh=Math.max(6,H*.032);
if (!REC) while (EV.length && EV[0].t + EV[0].d < now - 4) EV.shift();
for (const e of EV){
if (e.k==="drum") continue;
const x0=PX+(e.t-now)*PPS, w=e.d*PPS; if (x0+w<0||x0>W) continue;
const on=now>=e.t && now<e.t+e.d, past=now>=e.t+e.d;
if (e.k==="lead"){
rc.fillStyle = on ? "#a0d6ff" : past ? "rgba(255,255,255,.22)" : "rgba(255,255,255,.92)";
if (on){ rc.shadowColor="rgba(74,175,253,.95)"; rc.shadowBlur=22; }
rc.beginPath(); rc.roundRect(x0+1, y(e.m)-bh/2, Math.max(2,w-4), bh, bh/2); rc.fill(); rc.shadowBlur=0;
} else {
let m=e.m; while(m<MLO) m+=12;
rc.fillStyle = on ? "rgba(74,175,253,.26)" : "rgba(74,175,253,.11)";
rc.beginPath(); rc.roundRect(x0+1, y(m)-bh*.25, Math.max(2,w-4), bh*.5, bh*.25); rc.fill();
}
}
const gl=rc.createLinearGradient(0,0,W,0); gl.addColorStop(0,"#000"); gl.addColorStop(.16,"rgba(0,0,0,0)"); gl.addColorStop(.84,"rgba(0,0,0,0)"); gl.addColorStop(1,"#000");
rc.fillStyle=gl; rc.fillRect(0,0,W,H);
let pulse=0; for (const e of EV) if (e.k==="drum" && now>=e.t && now<e.t+.25) pulse=Math.max(pulse,1-(now-e.t)/.25);
const gp=rc.createLinearGradient(0,0,0,H); gp.addColorStop(0,"rgba(255,255,255,0)"); gp.addColorStop(.5,`rgba(255,255,255,${.55+.4*pulse})`); gp.addColorStop(1,"rgba(255,255,255,0)");
rc.fillStyle=gp; rc.fillRect(PX-1,0,2,H);
const [KW,KH,kd] = fit(keys); kc.setTransform(kd,0,0,kd,0,0); kc.clearRect(0,0,KW,KH);
const whites=[]; for (let m=KLO;m<=KHI;m++) if (WHITE.includes(m%12)) whites.push(m);
const ww=KW/whites.length, keyX=m=>whites.filter(w=>w<m).length*ww;
const lead=new Set(), soft=new Set();
for (const e of EV) if (e.k!=="drum" && now>=e.t && now<e.t+e.d){ let m=e.m; while(m<KLO) m+=12; while(m>KHI) m-=12; (e.k==="lead"?lead:soft).add(m); }
for (const m of whites){ const x=keyX(m);
kc.fillStyle = lead.has(m) ? "#4AAFFD" : soft.has(m) ? "rgba(74,175,253,.32)" : "rgba(255,255,255,.9)";
if (lead.has(m)){ kc.shadowColor="rgba(74,175,253,.9)"; kc.shadowBlur=18; }
kc.beginPath(); kc.roundRect(x+1, 0, ww-2, KH, [0,0,5,5]); kc.fill(); kc.shadowBlur=0; }
for (let m=KLO;m<=KHI;m++){ if (WHITE.includes(m%12)) continue; const x=keyX(m)-ww*.32;
kc.fillStyle = lead.has(m) ? "#4AAFFD" : soft.has(m) ? "#1d4a6b" : "#0b0b0d";
kc.beginPath(); kc.roundRect(x, 0, ww*.64, KH*.6, [0,0,3,3]); kc.fill(); }
}
// ── 녹화 모드(?rec): 이 파일의 합성 코드로 오디오를 오프라인 렌더하고, 프레임마다 시각을 정해 그린다 ──
// 커서가 장르를 누르면(예약) 다음 마디 첫 박에 바뀐다. 장르 순서 = REC_PLAN(마디 번호).
let REC = null;
const REC_PLAN = [{bar:0, g:"lofi"}, {bar:2, g:"jazz"}, {bar:4, g:"trap"}, {bar:6, g:"orchestra"}];
const REC_BARS = 8, REC_TAIL = 2.6, REC_T0 = .1;
function planGenre(b){ let g = REC_PLAN[0].g; for (const p of REC_PLAN) if (b >= p.bar) g = p.g; return g; }
function wav(buf){
const n = buf.length, ch = buf.numberOfChannels, out = new DataView(new ArrayBuffer(44 + n*ch*2));
const w = (o, s) => [...s].forEach((c,i)=>out.setUint8(o+i, c.charCodeAt(0)));
w(0,"RIFF"); out.setUint32(4, 36+n*ch*2, true); w(8,"WAVEfmt "); out.setUint32(16,16,true); out.setUint16(20,1,true); out.setUint16(22,ch,true);
out.setUint32(24,buf.sampleRate,true); out.setUint32(28,buf.sampleRate*ch*2,true); out.setUint16(32,ch*2,true); out.setUint16(34,16,true); w(36,"data"); out.setUint32(40,n*ch*2,true);
const data = [...Array(ch)].map((_,c)=>buf.getChannelData(c)); let o = 44, peak = 1e-9;
for (const d of data) for (let i=0;i<n;i++) peak = Math.max(peak, Math.abs(d[i]));
const k = .89 / peak;
for (let i=0;i<n;i++) for (let c=0;c<ch;c++){ out.setInt16(o, Math.max(-1,Math.min(1,data[c][i]*k))*32767, true); o+=2; }
let bin = ""; const u8 = new Uint8Array(out.buffer); for (let i=0;i<u8.length;i+=8192) bin += String.fromCharCode(...u8.subarray(i,i+8192));
return btoa(bin);
}
async function recRender(){
let dur = REC_T0; const barT = [];
for (let b=0;b<REC_BARS;b++){ barT.push(dur); dur += 16*60/GENRES[planGenre(b)].bpm/4; }
const end = dur, total = dur + REC_TAIL, sr = 44100;
const ctx = new OfflineAudioContext(2, Math.ceil(total*sr), sr);
setup(ctx); EV.length = 0;
let t = REC_T0, st = 0, cur = null;
for (let b=0;b<REC_BARS;b++){
const g = planGenre(b), s16 = 60/GENRES[g].bpm/4;
if (g !== cur){ genreAudio(g, t); cur = g; }
for (let k=0;k<16;k++){ playStep(g, st, t, s16); t += s16; st = (st+1) % 64; }
}
master.gain.setValueAtTime(.55, end); master.gain.linearRampToValueAtTime(0, total - .2);
const buf = await ctx.startRendering();
REC = { t:0, barT, end, total, clicks: REC_PLAN.slice(1).map(p => ({g:p.g, at: barT[p.bar] - 1.15, sw: barT[p.bar]})) };
return { wav: wav(buf), total, barT };
}
const ease = x => x<.5 ? 4*x*x*x : 1-Math.pow(-2*x+2,3)/2;
function btnCenter(g){ const r = document.querySelector(`#genres button[data-g="${g}"]`).getBoundingClientRect(); return [r.left + r.width*.55, r.top + r.height*.62]; }
function recSetT(t){
REC.t = t;
// 지금 장르·예약 상태
let g = REC_PLAN[0].g, pend = null;
for (const c of REC.clicks){ if (t >= c.sw) g = c.g; else if (t >= c.at) pend = c.g; }
document.querySelectorAll("#genres button").forEach(b => { b.classList.toggle("on", b.dataset.g===g); b.classList.toggle("pend", b.dataset.g===pend); });
const lab = document.getElementById("genre"); lab.textContent = GENRES[g].name;
let since = 9; for (const c of REC.clicks) if (t >= c.sw) since = t - c.sw;
lab.style.opacity = Math.min(1, since/.35); lab.style.transform = `translateY(${(1-Math.min(1,since/.35))*8}px)`;
// 커서: 사람 손처럼 — 휘는 경로, 빠르게 출발해 천천히 도착(최소 저크), 살짝 지나쳤다 되돌아옴(멈춰 있을 땐 가만히, 11-26)
const mj = x => x<=0 ? 0 : x>=1 ? 1 : x*x*x*(10 - 15*x + 6*x*x);
const jz = btnCenter("jazz"), rest0 = [jz[0] + 6, jz[1] + 64]; // 시작 = Jazz 버튼 아래(11-26)
let pos = rest0.slice(), hand = false, press = 0, rip = -1, hovG = null, from = rest0.slice();
REC.clicks.forEach((c, i) => {
const r = prng(4100 + i*17), [bx0, by0] = btnCenter(c.g);
const tx = bx0 + (r()-.5)*10, ty = by0 + (r()-.5)*6; // 버튼 한가운데가 아니라 매번 조금씩 다른 자리
const dur = .85 + r()*.25, arrive = c.at - .22, a = arrive - dur; // 도착 후 잠깐 머물렀다 누른다
const dx = tx - from[0], dy = ty - from[1], dist = Math.hypot(dx, dy) || 1;
const bend = (r() < .5 ? -1 : 1) * dist * (.12 + r()*.08); // 경로가 한쪽으로 휜다
const cx = from[0] + dx*.5 - dy/dist*bend, cy = from[1] + dy*.5 + dx/dist*bend;
const ov = 5 + r()*4; // 지나치는 거리(px)
if (t >= a && t < arrive){
const k = (t - a)/dur, e = mj(Math.min(1, k/.86));
let x = (1-e)*(1-e)*from[0] + 2*(1-e)*e*cx + e*e*tx, y = (1-e)*(1-e)*from[1] + 2*(1-e)*e*cy + e*e*ty;
if (k > .7){ const o = Math.sin(Math.min(1,(k-.7)/.3)*Math.PI) ; x += dx/dist*ov*o; y += dy/dist*ov*o*.6; }
pos = [x, y]; if (k > .8) { hand = true; hovG = c.g; }
}
const away = c.at + .5 + r()*.2, adur = .7 + r()*.2;
const rest = [tx + 30 + r()*40, ty + 60 + r()*50];
if (t >= arrive && t < away){ pos = [tx, ty]; hand = true; hovG = c.g;
const dt = t - c.at;
if (dt >= 0 && dt < .32){ press = dt < .07 ? dt/.07 : dt < .15 ? 1 : 1 - (dt-.15)/.17; } // 꾸욱 눌렀다 뗀다
if (dt >= 0 && dt < .5) rip = dt/.5; }
if (t >= away){
const k = mj(Math.min(1, (t-away)/adur));
const mx = (tx + rest[0])/2 + 14, my = (ty + rest[1])/2;
pos = [(1-k)*(1-k)*tx + 2*(1-k)*k*mx + k*k*rest[0], (1-k)*(1-k)*ty + 2*(1-k)*k*my + k*k*rest[1]];
if (k < .18) { hand = true; hovG = c.g; }
}
if (t >= a) from = rest;
else if (i === 0) pos = rest0.slice();
if (t >= a && t < away + adur) return;
});
// 가장 최근 구간만 쓰도록 다시 계산(위 루프는 시각 순서대로 덮어쓴다)
document.querySelectorAll("#genres button").forEach(b => b.classList.toggle("hov", b.dataset.g===hovG));
document.getElementById("cur-arrow").style.display = hand ? "none" : "block";
const hs = document.getElementById("cur-hand"); hs.style.display = hand ? "block" : "none";
hs.style.transform = `translate(-12px, ${-3 + press*1.5}px) scale(${1 - .16*press}, ${1 - .2*press})`;
document.getElementById("cursor").style.transform = `translate(${pos[0]}px, ${pos[1]}px)`;
const rp = document.getElementById("ripple");
if (rip >= 0){ const c = REC.clicks.filter(c => t >= c.at).pop(); const [bx,by] = btnCenter(c.g);
rp.style.opacity = (1-rip)*.55; rp.style.transform = `translate(${bx}px, ${by}px) scale(${.5+rip*1.1})`; } else rp.style.opacity = 0;
drawAt(t);
}
if (new URLSearchParams(location.search).has("rec")){
document.body.classList.add("rec");
window.recRender = recRender; window.recSetT = recSetT;
} else requestAnimationFrame(draw);
</script>
</body>
</html>
광고