İçeriğe geç
Tüm kodlar

Hipodrom

Yorumla oynanan TikTok LIVE at yarışı

459 satır · 14,7 KBHamİndir
// Ses: klasörde şarkı varsa onları çalar; yoksa tarayıcıda galop müziği üretir.
// Efektler: start borusu, kapı açılışı, nal sesleri, tribün uğultusu, bitiş zili, geri sayım.

const mtof = (m) => 440 * 2 ** ((m - 69) / 12);

// 2/4 galop. Her ölçü 4 sekizlik. [midi, uzunluk(sekizlik)], midi null = es
const SEC_A = [
  [[72, 1], [76, 1], [79, 1], [76, 1]],
  [[84, 2], [79, 1], [76, 1]],
  [[74, 1], [77, 1], [79, 1], [77, 1]],
  [[83, 2], [79, 2]],
  [[72, 1], [76, 1], [79, 1], [84, 1]],
  [[88, 1], [86, 1], [84, 1], [79, 1]],
  [[77, 1], [76, 1], [74, 1], [71, 1]],
  [[72, 2], [null, 2]],
];
const SEC_B = [
  [[77, 1], [81, 1], [84, 1], [81, 1]],
  [[89, 2], [84, 2]],
  [[76, 1], [79, 1], [84, 1], [79, 1]],
  [[88, 2], [84, 2]],
  [[86, 1], [84, 1], [83, 1], [81, 1]],
  [[79, 1], [77, 1], [76, 1], [74, 1]],
  [[72, 1], [76, 1], [79, 1], [84, 1]],
  [[84, 2], [null, 2]],
];
const CH_A = ['C', 'C', 'G', 'G', 'C', 'C', 'G', 'C'];
const CH_B = ['F', 'F', 'C', 'C', 'G', 'G', 'C', 'C'];
const CHORDS = { C: { root: 48, tri: [60, 64, 67] }, G: { root: 43, tri: [59, 62, 65] }, F: { root: 41, tri: [60, 65, 69] } };
const FORM = [['A', SEC_A, CH_A], ['A', SEC_A, CH_A], ['B', SEC_B, CH_B], ['A', SEC_A, CH_A]];

const PHASE = {
  lobby: { bpm: 108, lead: 0.05, drums: false, crowd: 0.025 },
  race: { bpm: 150, lead: 0.07, drums: true, crowd: 0.06 },
  final: { bpm: 166, lead: 0.085, drums: true, crowd: 0.16 },
  result: { bpm: 120, lead: 0.06, drums: true, crowd: 0.05 },
};

export function createAudio(rules = {}) {
  const AC = window.AudioContext || window.webkitAudioContext;
  const ctx = new AC();

  const comp = ctx.createDynamicsCompressor();
  comp.threshold.value = -12;
  comp.ratio.value = 4;
  comp.connect(ctx.destination);
  const master = ctx.createGain();
  master.gain.value = 0.9;
  master.connect(comp);
  const musicBus = ctx.createGain();
  musicBus.gain.value = 0.8;
  musicBus.connect(master);
  const sfxBus = ctx.createGain();
  sfxBus.connect(master);

  // ses düzeyleri (panelden ayarlanır)
  let musicVol = rules.volumes?.music ?? 0.7;
  let sfxVol = rules.volumes?.sfx ?? 0.8;
  let sonVol = rules.volumes?.sonses ?? 1;
  let ytOn = false; // YouTube çalarken oyunun kendi müziği susar
  let duck = 1; // son ses / boru çalarken müzik kısılır
  const musicLevel = () => (ytOn ? 0.0001 : Math.max(0.0001, 0.8 * musicVol * duck));
  const applyMusic = (tc = 0.3) => musicBus.gain.setTargetAtTime(musicLevel(), ctx.currentTime, tc);
  sfxBus.gain.value = sfxVol;
  musicBus.gain.value = musicLevel();

  // bitişe az kala çalan ses (web/public/sfx/sonses.mp4)
  const son = new Audio('/sfx/sonses.mp4');
  son.preload = 'auto';
  const sonGain = ctx.createGain();
  sonGain.gain.value = sonVol;
  ctx.createMediaElementSource(son).connect(sonGain).connect(master);
  let onDuck = () => {};
  son.addEventListener('ended', () => setDuck(1));
  function setDuck(d) {
    duck = d;
    applyMusic(0.4);
    onDuck(d);
  }

  const noiseBuf = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate);
  {
    const d = noiseBuf.getChannelData(0);
    for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
  }
  const noise = (t, dur, loop = false) => {
    const s = ctx.createBufferSource();
    s.buffer = noiseBuf;
    s.loop = loop;
    s.start(t, Math.random() * 1.5);
    if (dur) s.stop(t + dur);
    return s;
  };
  const env = (t, peak, attack, decay) => {
    const g = ctx.createGain();
    g.gain.setValueAtTime(0.0001, t);
    g.gain.exponentialRampToValueAtTime(Math.max(peak, 0.0002), t + attack);
    g.gain.exponentialRampToValueAtTime(0.0001, t + attack + decay);
    return g;
  };
  const tone = (t, freq, dur, type, peak, dest = musicBus, attack = 0.005) => {
    const o = ctx.createOscillator();
    o.type = type;
    o.frequency.value = freq;
    const g = env(t, peak, attack, dur);
    o.connect(g).connect(dest);
    o.start(t);
    o.stop(t + attack + dur + 0.05);
    return o;
  };

  // ---------- Tribün uğultusu (sürekli) ----------
  const crowdGain = ctx.createGain();
  crowdGain.gain.value = 0.0001;
  {
    const n = noise(ctx.currentTime, 0, true);
    const bp = ctx.createBiquadFilter();
    bp.type = 'bandpass';
    bp.frequency.value = 950;
    bp.Q.value = 0.45;
    const lfo = ctx.createOscillator();
    lfo.frequency.value = 0.23;
    const lfoG = ctx.createGain();
    lfoG.gain.value = 250;
    lfo.connect(lfoG).connect(bp.frequency);
    lfo.start();
    n.connect(bp).connect(crowdGain).connect(sfxBus);
  }

  // ---------- Galop müziği ----------
  let phase = 'lobby';
  let mode = 'synth';
  let running = false;
  let bpm = PHASE.lobby.bpm;
  let nextStep = 0;
  let step = 0; // sekizlik sayacı
  let formIdx = 0;
  let barIdx = 0;
  let noteLeft = 0;
  let noteQueue = [];

  function lead(t, midi, dur, level) {
    const lp = ctx.createBiquadFilter();
    lp.type = 'lowpass';
    lp.frequency.setValueAtTime(5200, t);
    lp.frequency.exponentialRampToValueAtTime(2200, t + dur);
    const g = ctx.createGain();
    g.gain.setValueAtTime(0.0001, t);
    g.gain.exponentialRampToValueAtTime(level, t + 0.006);
    g.gain.setValueAtTime(level * 0.8, t + dur * 0.7);
    g.gain.exponentialRampToValueAtTime(0.0001, t + dur * 0.98);
    for (const [type, det, lvl] of [['square', 0, 0.6], ['sawtooth', 8, 0.35]]) {
      const o = ctx.createOscillator();
      o.type = type;
      o.frequency.value = mtof(midi);
      o.detune.value = det;
      const og = ctx.createGain();
      og.gain.value = lvl;
      o.connect(og).connect(lp);
      o.start(t);
      o.stop(t + dur + 0.05);
    }
    lp.connect(g).connect(musicBus);
  }
  function snare(t, v) {
    const n = noise(t, 0.12);
    const hp = ctx.createBiquadFilter();
    hp.type = 'highpass';
    hp.frequency.value = 1500;
    n.connect(hp).connect(env(t, 0.18 * v, 0.002, 0.09)).connect(musicBus);
  }
  function kick(t) {
    const o = ctx.createOscillator();
    o.frequency.setValueAtTime(120, t);
    o.frequency.exponentialRampToValueAtTime(45, t + 0.12);
    o.connect(env(t, 0.5, 0.003, 0.18)).connect(musicBus);
    o.start(t);
    o.stop(t + 0.25);
  }

  function scheduleStep(i, t) {
    const P = PHASE[phase];
    const sd = 60 / bpm / 2;
    const [, sec, chords] = FORM[formIdx];
    const pos = i % 4; // ölçü içinde sekizlik
    const ch = CHORDS[chords[barIdx]];

    // um-pa: kalın ses vuruşta, akor arada
    if (pos === 0 || pos === 2) {
      const root = pos === 0 ? ch.root : ch.root + 7;
      tone(t, mtof(root), sd * 1.4, 'triangle', 0.32);
      tone(t, mtof(root - 12), sd * 1.2, 'sine', 0.22);
      if (P.drums) kick(t);
    } else {
      for (const m of ch.tri) tone(t, mtof(m), sd * 0.55, 'square', 0.028);
      if (P.drums) snare(t, pos === 3 ? 1 : 0.7);
    }
    if (P.drums && phase === 'final') snare(t + sd / 2, 0.35);

    // melodi
    if (noteLeft <= 0) {
      if (!noteQueue.length) noteQueue = sec[barIdx].slice();
      const [m, l] = noteQueue.shift();
      noteLeft = l;
      if (m != null) lead(t, phase === 'lobby' ? m - 12 : m, l * sd * 0.92, P.lead);
    }
    noteLeft--;

    if (pos === 3) {
      barIdx++;
      noteQueue = [];
      noteLeft = 0;
      if (barIdx >= 8) {
        barIdx = 0;
        formIdx = (formIdx + 1) % FORM.length;
      }
    }
  }

  // ---------- Nal sesleri ----------
  let hoofLevel = 0;
  let strideHz = 2.2;
  let nextHoof = 0;
  function hoof(t, v) {
    const n = noise(t, 0.06);
    const lp = ctx.createBiquadFilter();
    lp.type = 'lowpass';
    lp.frequency.value = 520;
    n.connect(lp).connect(env(t, 0.5 * v, 0.002, 0.05)).connect(sfxBus);
    const o = ctx.createOscillator();
    o.frequency.setValueAtTime(90, t);
    o.frequency.exponentialRampToValueAtTime(50, t + 0.05);
    o.connect(env(t, 0.25 * v, 0.002, 0.05)).connect(sfxBus);
    o.start(t);
    o.stop(t + 0.1);
  }

  function tick() {
    const ahead = ctx.currentTime + 0.15;
    if (running && mode === 'synth') {
      if (nextStep < ctx.currentTime) nextStep = ctx.currentTime + 0.05;
      while (nextStep < ahead) {
        scheduleStep(step, nextStep);
        nextStep += 60 / bpm / 2;
        step++;
      }
    }
    if (hoofLevel > 0.01) {
      if (nextHoof < ctx.currentTime) nextHoof = ctx.currentTime + 0.02;
      while (nextHoof < ahead) {
        // dört nal: ta-ta-ta ... dum
        const stride = 1 / strideHz;
        const v = hoofLevel * (0.7 + Math.random() * 0.3);
        hoof(nextHoof, v);
        hoof(nextHoof + stride * 0.11, v * 0.8);
        hoof(nextHoof + stride * 0.2, v * 0.9);
        hoof(nextHoof + stride * 0.31, v);
        nextHoof += stride;
      }
    }
  }
  setInterval(tick, 25);

  // ---------- Klasördeki şarkılar ----------
  let files = [];
  let fileIdx = 0;
  let el = null;
  function playFile() {
    if (!files.length) return;
    if (!el) {
      el = new Audio();
      ctx.createMediaElementSource(el).connect(musicBus);
      el.addEventListener('ended', () => next());
      el.addEventListener('error', () => setTimeout(next, 500));
    }
    el.src = '/music/' + encodeURIComponent(files[fileIdx % files.length]);
    el.play().catch(() => {});
  }
  function next() {
    if (mode !== 'files') return;
    fileIdx++;
    if (fileIdx % files.length === 0) files.sort(() => Math.random() - 0.5);
    playFile();
  }

  async function init() {
    try {
      const r = await fetch('/api/music');
      if (r.ok) files = (await r.json()).sort(() => Math.random() - 0.5);
    } catch { /* sunucu yok */ }
    if (files.length) {
      mode = 'files';
      if (!ytOn) playFile();
    } else {
      running = true;
      nextStep = ctx.currentTime + 0.1;
    }
    setPhase(phase);
  }

  function setPhase(p) {
    if (!PHASE[p]) return;
    phase = p;
    bpm = PHASE[p].bpm;
    crowdGain.gain.setTargetAtTime(PHASE[p].crowd, ctx.currentTime, 0.8);
    applyMusic();
  }

  // ---------- Efektler ----------
  function brass(t, midi, dur, level = 0.12) {
    const lp = ctx.createBiquadFilter();
    lp.type = 'lowpass';
    lp.Q.value = 2;
    lp.frequency.setValueAtTime(600, t);
    lp.frequency.exponentialRampToValueAtTime(3800, t + 0.05);
    lp.frequency.exponentialRampToValueAtTime(2400, t + dur);
    const g = ctx.createGain();
    g.gain.setValueAtTime(0.0001, t);
    g.gain.exponentialRampToValueAtTime(level, t + 0.03);
    g.gain.setValueAtTime(level * 0.85, t + dur * 0.8);
    g.gain.exponentialRampToValueAtTime(0.0001, t + dur + 0.04);
    const o = ctx.createOscillator();
    o.type = 'sawtooth';
    o.frequency.setValueAtTime(mtof(midi) * 0.97, t);
    o.frequency.exponentialRampToValueAtTime(mtof(midi), t + 0.04);
    const vib = ctx.createOscillator();
    vib.frequency.value = 5;
    const vg = ctx.createGain();
    vg.gain.value = dur > 0.5 ? 3 : 0;
    vib.connect(vg).connect(o.frequency);
    o.connect(lp).connect(g).connect(sfxBus);
    o.start(t);
    vib.start(t);
    o.stop(t + dur + 0.1);
    vib.stop(t + dur + 0.1);
  }
  // Start borusu: sadece doğal borazan sesleri (Sol-Do-Mi-Sol)
  function bugle() {
    const t0 = ctx.currentTime + 0.05;
    musicBus.gain.setTargetAtTime(musicLevel() * 0.2, t0 - 0.04, 0.05);
    musicBus.gain.setTargetAtTime(musicLevel(), t0 + 3.4, 0.4);
    const u = 0.16;
    const call = [
      [67, 1], [67, 1], [72, 1], [76, 2], [72, 1], [76, 1], [79, 3],
      [76, 1], [79, 1], [79, 1], [79, 1], [76, 1], [72, 1], [76, 2], [67, 2], [72, 5],
    ];
    let t = t0;
    for (const [m, l] of call) {
      brass(t, m, l * u * 0.9);
      t += l * u;
    }
    return t - t0;
  }
  function gate() {
    const t = ctx.currentTime + 0.01;
    const n = noise(t, 0.3);
    const bp = ctx.createBiquadFilter();
    bp.type = 'bandpass';
    bp.frequency.value = 2500;
    n.connect(bp).connect(env(t, 0.4, 0.002, 0.25)).connect(sfxBus);
    for (const f of [523, 1187, 1733]) tone(t, f, 0.5, 'sine', 0.06, sfxBus, 0.002);
    hoof(t + 0.05, 1);
    hoof(t + 0.1, 1);
  }
  function bell() {
    const t = ctx.currentTime + 0.01;
    for (let k = 0; k < 6; k++) {
      const tt = t + k * 0.11;
      for (const [f, a] of [[880, 0.12], [2210, 0.06], [3130, 0.04], [4600, 0.025]]) tone(tt, f, 0.9, 'sine', a, sfxBus, 0.001);
    }
  }
  function beep(high = false) {
    tone(ctx.currentTime + 0.01, high ? 1320 : 880, high ? 0.5 : 0.15, 'square', 0.05, sfxBus, 0.003);
  }
  function cheer(dur = 3) {
    const t = ctx.currentTime + 0.02;
    const n = noise(t, dur + 0.3);
    const bp = ctx.createBiquadFilter();
    bp.type = 'bandpass';
    bp.frequency.value = 1150;
    bp.Q.value = 0.5;
    const g = ctx.createGain();
    g.gain.setValueAtTime(0.0001, t);
    g.gain.exponentialRampToValueAtTime(0.28, t + 0.2);
    g.gain.setValueAtTime(0.28, t + dur * 0.5);
    g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
    n.connect(bp).connect(g).connect(sfxBus);
    for (let i = 0; i < 4; i++) {
      const tt = t + Math.random() * dur * 0.6;
      const o = ctx.createOscillator();
      const f = 1800 + Math.random() * 800;
      o.frequency.setValueAtTime(f, tt);
      o.frequency.linearRampToValueAtTime(f * 1.3, tt + 0.25);
      o.frequency.linearRampToValueAtTime(f * 0.9, tt + 0.55);
      o.connect(env(tt, 0.045, 0.04, 0.5)).connect(sfxBus);
      o.start(tt);
      o.stop(tt + 0.7);
    }
  }

  return {
    init,
    // panelden ses düzeyi: music | sfx | sonses (0..1)
    setVolume(key, v) {
      v = Math.max(0, Math.min(1, Number(v) || 0));
      if (key === 'music') {
        musicVol = v;
        applyMusic(0.1);
      } else if (key === 'sfx') {
        sfxVol = v;
        sfxBus.gain.setTargetAtTime(Math.max(0.0001, v), ctx.currentTime, 0.1);
      } else if (key === 'sonses') {
        sonVol = v;
        sonGain.gain.setTargetAtTime(Math.max(0.0001, v), ctx.currentTime, 0.1);
      }
    },
    setYoutube(on) {
      ytOn = !!on;
      applyMusic(0.5);
      if (el) {
        if (ytOn) el.pause();
        else if (mode === 'files') el.play().catch(() => {});
      }
    },
    sonDuration: () => (Number.isFinite(son.duration) && son.duration > 0 ? son.duration : 17.2),
    playSon() {
      try {
        son.currentTime = 0;
      } catch { /* yüklenmedi */ }
      // Bitiş sesi dosyası yoksa müzik kısılmasın (sfx/sonses.mp4 isteğe bağlı)
      son.play().then(() => setDuck(0.3)).catch(() => {});
    },
    stopSon() {
      if (!son.paused) son.pause();
      if (duck !== 1) setDuck(1);
    },
    onDuck(fn) {
      onDuck = fn;
    },
    setPhase,
    next,
    bugle,
    gate,
    bell,
    beep,
    cheer,
    needsUnlock: () => ctx.state !== 'running',
    unlock: () => ctx.resume().then(() => {
      if (mode === 'files' && el?.paused) el.play().catch(() => {});
    }),
    setHooves(level, hz) {
      hoofLevel = Math.max(0, Math.min(1, level));
      if (hz) strideHz = hz;
    },
    setCrowd(level) {
      crowdGain.gain.setTargetAtTime(Math.max(0.0001, level), ctx.currentTime, 0.3);
    },
  };
}

Lisans bilgisi projenin LICENSE dosyasında.