features.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /* Features page: the step sequencer and the demo-song player. */
  2. (() => {
  3. const $ = s => document.querySelector(s), $$ = s => [...document.querySelectorAll(s)];
  4. const t = (...a) => window.LYNX_T ? window.LYNX_T(...a) : a[0];
  5. /* ---------- step sequencer (Web Audio) ---------- */
  6. const seqEl = $('#seq');
  7. let playing = false, stopSeq = () => {};
  8. const audio = $('#audio');
  9. if (seqEl){
  10. const rows = [
  11. {n:'Kick', c:'#e5383b', p:[0,4,8,12]}, {n:'Clap', c:'#f4a259', p:[4,12]}, {n:'Hat', c:'#e9c46a', p:[2,6,10,14]},
  12. {n:'Snare', c:'#c77dff', p:[15]}, {n:'Bass', c:'#4cc9f0', p:[0,3,6,10,11]}, {n:'Pluck', c:'#3ddc84', p:[2,7,9,14]}
  13. ];
  14. const grid = rows.map(r => Array.from({length:16}, (_, i) => r.p.includes(i)));
  15. rows.forEach((r, ri) => {
  16. const row = document.createElement('div'); row.className = 'row'; row.style.setProperty('--c', r.c);
  17. row.innerHTML = `<div class="nm">${r.n}</div>`;
  18. for (let s = 0; s < 16; s++){
  19. const b = document.createElement('button'); b.className = 'cell' + (grid[ri][s] ? ' on' : ''); b.dataset.step = s + 1;
  20. b.onclick = () => { grid[ri][s] = !grid[ri][s]; b.classList.toggle('on', grid[ri][s]); if (grid[ri][s]){ ensureCtx(); voice(ri, ctx.currentTime, s); } };
  21. row.appendChild(b);
  22. }
  23. seqEl.appendChild(row);
  24. });
  25. const cells = $$('#seq .row').map(r => [...r.querySelectorAll('.cell')]);
  26. const label = () => cells.forEach((rc, r) => rc.forEach(c => c.setAttribute('aria-label', t('aria.step', rows[r].n, c.dataset.step))));
  27. label(); document.addEventListener('lynx:lang', label);
  28. let ctx, master, noiseBuf, step = 0, nextT = 0, timer;
  29. function ensureCtx(){
  30. if (ctx){ if (ctx.state === 'suspended') ctx.resume(); return; }
  31. ctx = new (window.AudioContext || window.webkitAudioContext)();
  32. const comp = ctx.createDynamicsCompressor(); comp.threshold.value = -14; comp.ratio.value = 4;
  33. master = ctx.createGain(); master.gain.value = .8; master.connect(comp); comp.connect(ctx.destination);
  34. noiseBuf = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate); const d = noiseBuf.getChannelData(0); for (let i = 0; i < d.length; i++) d[i] = Math.random()*2 - 1;
  35. }
  36. const bassNotes = [36,36,39,36,43,41,36,34,36,36,39,41,43,46,43,39], pluckNotes = [72,75,79,82,79,75,77,74,72,75,79,84,82,79,77,75];
  37. const hz = m => 440*Math.pow(2, (m - 69)/12);
  38. function env(g, t, a, peak, dec){ g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(peak, t + a); g.gain.exponentialRampToValueAtTime(0.0001, t + a + dec); }
  39. function noise(t, dec, type, freq, q, vol){ const s = ctx.createBufferSource(); s.buffer = noiseBuf; const f = ctx.createBiquadFilter(); f.type = type; f.frequency.value = freq; f.Q.value = q; const g = ctx.createGain(); env(g, t, .001, vol, dec); s.connect(f); f.connect(g); g.connect(master); s.start(t); s.stop(t + dec + .05); }
  40. function voice(r, t, s){
  41. if (r === 0){ const o = ctx.createOscillator(), g = ctx.createGain(); o.frequency.setValueAtTime(160, t); o.frequency.exponentialRampToValueAtTime(42, t + .12); env(g, t, .002, 1, .38); o.connect(g); g.connect(master); o.start(t); o.stop(t + .45); }
  42. else if (r === 1){ [0, .011, .022].forEach(d => noise(t + d, .16, 'bandpass', 1400, 1.2, .55)); }
  43. else if (r === 2){ noise(t, .05, 'highpass', 8000, .7, .32); }
  44. else if (r === 3){ noise(t, .2, 'bandpass', 2200, .8, .6); const o = ctx.createOscillator(), g = ctx.createGain(); o.frequency.value = 190; env(g, t, .001, .4, .12); o.connect(g); g.connect(master); o.start(t); o.stop(t + .2); }
  45. else if (r === 4){ const f = ctx.createBiquadFilter(), g = ctx.createGain(); f.type = 'lowpass'; f.Q.value = 6; f.frequency.setValueAtTime(1600, t); f.frequency.exponentialRampToValueAtTime(140, t + .22);
  46. [0, -8, 8].forEach(dt => { const o = ctx.createOscillator(); o.type = 'sawtooth'; o.frequency.value = hz(bassNotes[s]); o.detune.value = dt; o.connect(f); o.start(t); o.stop(t + .32); });
  47. env(g, t, .004, .28, .26); f.connect(g); g.connect(master); }
  48. else { const o = ctx.createOscillator(), o2 = ctx.createOscillator(), f = ctx.createBiquadFilter(), g = ctx.createGain(); o.type = 'square'; o2.type = 'sawtooth'; o.frequency.value = hz(pluckNotes[s]); o2.frequency.value = hz(pluckNotes[s])*1.005;
  49. f.type = 'lowpass'; f.frequency.setValueAtTime(5000, t); f.frequency.exponentialRampToValueAtTime(400, t + .25); env(g, t, .003, .12, .35); o.connect(f); o2.connect(f); f.connect(g); g.connect(master); o.start(t); o2.start(t); o.stop(t + .4); o2.stop(t + .4); }
  50. }
  51. function paint(s){ cells.forEach(rc => rc.forEach((c, i) => c.classList.toggle('now', i === s && playing))); }
  52. function schedule(){
  53. const bpm = +$('#bpm').value, sw = +$('#swing').value/100, sd = 60/bpm/4;
  54. while (nextT < ctx.currentTime + .12){
  55. const tt = nextT + (step % 2 ? sd*sw*.66 : 0);
  56. rows.forEach((_, r) => { if (grid[r][step]) voice(r, tt, step); });
  57. const s = step; setTimeout(() => paint(s), Math.max(0, (tt - ctx.currentTime)*1000));
  58. nextT += sd; step = (step + 1) % 16;
  59. }
  60. }
  61. const sp = $('#seqPlay'), playIc = sp.innerHTML, stopIc = '<svg viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"/></svg>';
  62. sp.onclick = () => {
  63. ensureCtx(); playing = !playing; sp.innerHTML = playing ? stopIc : playIc;
  64. if (playing){ if (audio && !audio.paused) audio.pause(); step = 0; nextT = ctx.currentTime + .05; timer = setInterval(schedule, 25); schedule(); }
  65. else { clearInterval(timer); paint(-1); }
  66. };
  67. stopSeq = () => { if (playing) sp.click(); };
  68. $('#bpm').oninput = e => $('#bpmv').textContent = e.target.value;
  69. $('#rnd').onclick = () => grid.forEach((g, r) => g.forEach((_, i) => { const prob = [.3,.12,.5,.08,.3,.25][r]; g[i] = r === 0 ? i % 4 === 0 || Math.random() < .08 : Math.random() < prob; cells[r][i].classList.toggle('on', g[i]); }));
  70. $('#clr').onclick = () => grid.forEach((g, r) => g.forEach((_, i) => { g[i] = false; cells[r][i].classList.remove('on'); }));
  71. }
  72. /* ---------- demo song with waveform ---------- */
  73. const wave = $('#wave');
  74. if (wave && audio){
  75. const wc = wave.querySelector('canvas'), wx = wc.getContext('2d'), ap = $('#aPlay'), at = $('#atime'), tour = $('#tour');
  76. const playIc = ap.innerHTML, stopIc = '<svg viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"/></svg>';
  77. let peaks = [];
  78. fetch('/assets/media/peaks.json?v=0.1.27').then(r => r.json()).then(p => { peaks = p; draw(); }).catch(() => {});
  79. function draw(){
  80. const d = Math.min(devicePixelRatio || 1, 2), w = wave.clientWidth, h = wave.clientHeight; wc.width = w*d; wc.height = h*d; wx.setTransform(d, 0, 0, d, 0, 0);
  81. wx.clearRect(0, 0, w, h); if (!peaks.length) return;
  82. const n = Math.floor(w/3), pos = audio.duration ? audio.currentTime/audio.duration : 0;
  83. for (let i = 0; i < n; i++){
  84. const bh = Math.max(2, peaks[Math.floor(i/n*peaks.length)]*h*.92);
  85. wx.fillStyle = i/n < pos ? '#e5383b' : '#3a3d4a';
  86. wx.fillRect(i*3, (h - bh)/2, 2, bh);
  87. }
  88. }
  89. addEventListener('resize', draw);
  90. const fmt = s => Math.floor(s/60) + ':' + String(Math.floor(s % 60)).padStart(2, '0');
  91. function tick(){ draw(); at.textContent = fmt(audio.currentTime) + ' / ' + fmt(audio.duration || 46); if (!audio.paused) requestAnimationFrame(tick); }
  92. ap.onclick = () => { if (audio.paused){ stopSeq(); if (tour) tour.pause(); audio.play(); } else audio.pause(); };
  93. audio.onplay = () => { ap.innerHTML = stopIc; tick(); };
  94. audio.onpause = audio.onended = () => { ap.innerHTML = playIc; tick(); };
  95. wave.onclick = e => { const r = wave.getBoundingClientRect(), f = (e.clientX - r.left)/r.width;
  96. const go = () => { audio.currentTime = f*audio.duration; tick(); };
  97. if (audio.readyState < 1){ audio.preload = 'auto'; audio.addEventListener('loadedmetadata', go, {once:true}); audio.load(); } else go(); };
  98. if (tour) tour.addEventListener('play', () => { stopSeq(); if (!audio.paused) audio.pause(); });
  99. }
  100. })();