İçeriğe geç
348 satır · 11,3 KBHamİndir
// Müzik: web/public/music içindeki şarkıları sırayla çalar (geçişli).
// Klasör boşsa kodla üretilen bir ritim döngüsü çalar.
// Bas vuruşlarını algılar -> dans, pist ve ışıklar müzikle senkron olur.

import { createYoutube } from './youtube.js';

const HICAZ = { A3: 220, Bb3: 233.08, Cs4: 277.18, D4: 293.66, E4: 329.63, F4: 349.23, G4: 392, A4: 440, Bb4: 466.16, Cs5: 554.37, D5: 587.33, E5: 659.25 };

export function createAudio({ volume = 0.6, crossfade = 3, youtube = null } = {}) {
  const ctx = new (window.AudioContext || window.webkitAudioContext)();
  const master = ctx.createGain();
  master.gain.value = volume;
  const analyser = ctx.createAnalyser();
  analyser.fftSize = 1024;
  analyser.smoothingTimeConstant = 0.6;
  master.connect(analyser);
  analyser.connect(ctx.destination);
  const freq = new Uint8Array(analyser.frequencyBinCount);

  let tracks = [];
  let index = -1;
  let mode = 'none'; // 'files' | 'synth'
  let current = null; // { el, gain }
  let nowPlaying = '';
  let onTrackCb = () => {};
  let switching = false;

  // ---------- Dosya çalma ----------
  function makeDeck() {
    const el = new Audio();
    el.crossOrigin = 'anonymous';
    el.preload = 'auto';
    const src = ctx.createMediaElementSource(el);
    const gain = ctx.createGain();
    gain.gain.value = 0;
    src.connect(gain).connect(master);
    return { el, gain };
  }
  const decks = [];

  async function playIndex(i) {
    if (!tracks.length) return;
    switching = true;
    index = ((i % tracks.length) + tracks.length) % tracks.length;
    if (decks.length < 2) decks.push(makeDeck(), makeDeck());
    const next = decks.find((d) => d !== current);
    const prev = current;
    next.el.src = '/music/' + encodeURIComponent(tracks[index]);
    next.el.currentTime = 0;
    const now = ctx.currentTime;
    next.gain.gain.cancelScheduledValues(now);
    next.gain.gain.setValueAtTime(0, now);
    next.gain.gain.linearRampToValueAtTime(1, now + (prev ? crossfade : 0.3));
    try {
      await next.el.play();
    } catch (e) {
      console.warn('[müzik] çalınamadı:', tracks[index], e.message);
    }
    if (prev) {
      prev.gain.gain.cancelScheduledValues(now);
      prev.gain.gain.setValueAtTime(prev.gain.gain.value, now);
      prev.gain.gain.linearRampToValueAtTime(0, now + crossfade);
      const old = prev.el;
      setTimeout(() => old.pause(), crossfade * 1000 + 100);
    }
    current = next;
    nowPlaying = tracks[index].replace(/\.[^.]+$/, '').replace(/[_-]+/g, ' ');
    onTrackCb(nowPlaying);
    switching = false;
  }

  // ---------- Üretilen ritim (dosya yoksa) ----------
  const synth = (() => {
    const bpm = 118;
    const spb = 60 / bpm;
    let nextTime = 0;
    let step = 0; // 16'lık adım
    let timer = null;
    let startTime = 0;
    const noiseBuf = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);
    const nd = noiseBuf.getChannelData(0);
    for (let i = 0; i < nd.length; i++) nd[i] = Math.random() * 2 - 1;
    const out = ctx.createGain();
    out.gain.value = 0.8;
    out.connect(master);

    const env = (g, t, a, peak, d) => {
      g.gain.setValueAtTime(0.0001, t);
      g.gain.exponentialRampToValueAtTime(peak, t + a);
      g.gain.exponentialRampToValueAtTime(0.0001, t + a + d);
    };
    function kick(t) {
      const o = ctx.createOscillator();
      const g = ctx.createGain();
      o.frequency.setValueAtTime(140, t);
      o.frequency.exponentialRampToValueAtTime(45, t + 0.15);
      env(g, t, 0.002, 1, 0.25);
      o.connect(g).connect(out);
      o.start(t);
      o.stop(t + 0.3);
    }
    function noise(t, type, f, peak, d) {
      const s = ctx.createBufferSource();
      s.buffer = noiseBuf;
      const flt = ctx.createBiquadFilter();
      flt.type = type;
      flt.frequency.value = f;
      const g = ctx.createGain();
      env(g, t, 0.001, peak, d);
      s.connect(flt).connect(g).connect(out);
      s.start(t, Math.random() * 0.5);
      s.stop(t + d + 0.05);
    }
    function darbuka(t, hi) {
      const o = ctx.createOscillator();
      const g = ctx.createGain();
      o.frequency.setValueAtTime(hi ? 420 : 190, t);
      o.frequency.exponentialRampToValueAtTime(hi ? 300 : 120, t + 0.08);
      env(g, t, 0.001, hi ? 0.25 : 0.45, hi ? 0.07 : 0.18);
      o.connect(g).connect(out);
      o.start(t);
      o.stop(t + 0.25);
      if (hi) noise(t, 'highpass', 3000, 0.12, 0.04);
    }
    function tone(t, f, dur, type, peak, cutoff) {
      const o = ctx.createOscillator();
      o.type = type;
      o.frequency.value = f;
      const flt = ctx.createBiquadFilter();
      flt.type = 'lowpass';
      flt.frequency.value = cutoff;
      const g = ctx.createGain();
      env(g, t, 0.01, peak, dur);
      o.connect(flt).connect(g).connect(out);
      o.start(t);
      o.stop(t + dur + 0.05);
    }
    // 2 ölçülük bas ve 4 ölçülük melodi (hicaz makamı havasında)
    const bass = [110, 110, 116.54, 110, 98, 110, 138.59, 110];
    const N = HICAZ;
    const melody = [
      N.A4, null, N.Bb4, N.Cs5, N.D5, null, N.Cs5, N.Bb4, N.A4, null, null, N.G4, N.A4, null, null, null,
      N.E5, null, N.D5, N.Cs5, N.D5, null, N.Cs5, N.Bb4, N.Cs5, null, N.Bb4, N.A4, N.Bb4, null, null, null,
      N.A4, null, N.Bb4, N.Cs5, N.E5, null, N.D5, N.Cs5, N.D5, N.E5, N.D5, N.Cs5, N.Bb4, null, N.A4, null,
      N.G4, null, N.A4, N.Bb4, N.A4, null, N.G4, N.F4, N.E4, null, null, null, N.A4, null, null, null,
    ];
    // düm-tek-tek-düm-tek kalıbı (16'lık adımlar)
    const dum = new Set([0, 6, 8]);
    const tek = new Set([4, 7, 12, 14]);

    function schedule() {
      while (nextTime < ctx.currentTime + 0.15) {
        const s = step % 16;
        const t = nextTime;
        if (s % 4 === 0) kick(t);
        if (s === 4 || s === 12) noise(t, 'bandpass', 1500, 0.35, 0.12);
        if (s % 2 === 1) noise(t, 'highpass', 7000, 0.08, 0.03);
        if (dum.has(s)) darbuka(t, false);
        if (tek.has(s)) darbuka(t, true);
        if (s % 4 === 0) tone(t, bass[Math.floor(step / 4) % bass.length], spb * 0.9, 'sawtooth', 0.22, 500);
        if (s % 2 === 0) {
          const f = melody[Math.floor(step / 2) % melody.length];
          if (f) tone(t, f, spb * 0.45, 'square', 0.07, 2200);
        }
        nextTime += spb / 4;
        step++;
      }
    }
    return {
      bpm,
      start() {
        if (timer) return;
        nextTime = ctx.currentTime + 0.05;
        startTime = nextTime;
        step = 0;
        timer = setInterval(schedule, 25);
      },
      stop() {
        clearInterval(timer);
        timer = null;
      },
      phase() {
        return (ctx.currentTime - startTime) / spb;
      },
      running: () => !!timer,
    };
  })();

  // ---------- Vuruş algılama ----------
  const beat = { pulse: 0, phase: 0, level: 0 };
  let bpm = 120;
  let avg = 0;
  let lastBeatAt = 0;
  const intervals = [];

  function detect(dt) {
    analyser.getByteFrequencyData(freq);
    // ~40-150 Hz bas bandı
    const binHz = ctx.sampleRate / analyser.fftSize;
    const lo = Math.max(1, Math.floor(40 / binHz));
    const hi = Math.ceil(150 / binHz);
    let sum = 0;
    for (let i = lo; i <= hi; i++) sum += freq[i];
    const energy = sum / ((hi - lo + 1) * 255);
    avg = avg * 0.95 + energy * 0.05;
    beat.level = energy;
    const now = performance.now() / 1000;
    if (energy > avg * 1.25 && energy > 0.25 && now - lastBeatAt > 0.3) {
      const iv = now - lastBeatAt;
      lastBeatAt = now;
      beat.pulse = 1;
      if (iv < 1.5) {
        intervals.push(iv);
        if (intervals.length > 12) intervals.shift();
        const sorted = [...intervals].sort((a, b) => a - b);
        let b = 60 / sorted[Math.floor(sorted.length / 2)];
        while (b < 80) b *= 2;
        while (b > 165) b /= 2;
        bpm = bpm * 0.8 + b * 0.2;
      }
      // fazı en yakın tam vuruşa çek
      const frac = beat.phase - Math.round(beat.phase);
      beat.phase -= frac * 0.5;
    }
    beat.phase += (bpm / 60) * dt;
  }

  // ---------- YouTube ----------
  let ytUrl = youtube?.url || '';
  const ytBpm = Number(youtube?.bpm) || 120;
  let yt = null;
  function getYt() {
    if (!yt) {
      yt = createYoutube({
        volume,
        onTitle: (title) => {
          nowPlaying = title;
          onTrackCb(nowPlaying);
        },
        onError: (msg) => console.warn('[youtube]', msg),
      });
    }
    return yt;
  }
  function stopLocal() {
    synth.stop();
    for (const d of decks) {
      d.el.pause();
      d.gain.gain.cancelScheduledValues(ctx.currentTime);
      d.gain.gain.value = 0;
    }
    current = null;
  }

  const api = {
    ctx,
    get nowPlaying() { return nowPlaying; },
    get mode() { return mode; },
    get needsGesture() {
      if (mode === 'youtube') return getYt().needsGesture;
      return ctx.state !== 'running';
    },
    onTrack(cb) { onTrackCb = cb; },
    /** Panelden YouTube linki değişince: boş link -> mp3 / ritme geri dön. */
    async setYoutube(url) {
      ytUrl = url || '';
      if (ytUrl) {
        stopLocal();
        mode = 'youtube';
        nowPlaying = 'YouTube yükleniyor…';
        onTrackCb(nowPlaying);
        await getYt().play(ytUrl);
      } else {
        yt?.stop();
        mode = 'none';
        await api.start();
      }
    },
    async load() {
      try {
        const r = await fetch('/api/music');
        tracks = r.ok ? await r.json() : [];
      } catch {
        tracks = [];
      }
      // karışık sırayla başla
      tracks.sort(() => Math.random() - 0.5);
    },
    /** Gerçekten ses çalıyor mu? */
    get playing() {
      if (mode === 'youtube') return !!yt?.playing;
      return mode !== 'none' && ctx.state === 'running';
    },
    async start() {
      // YouTube: dokunma anında, hiç beklemeden çal (iPhone dokunuşu kaybetmesin)
      if (mode === 'youtube') {
        getYt().resume();
        try { await ctx.resume(); } catch { /* izin yok */ }
        return;
      }
      try { await ctx.resume(); } catch { /* izin yok */ }
      if (mode !== 'none') return;
      if (ytUrl) {
        await api.setYoutube(ytUrl);
      } else if (tracks.length) {
        mode = 'files';
        await playIndex(0);
      } else {
        mode = 'synth';
        synth.start();
        nowPlaying = 'Gece Ritmi (otomatik)';
        onTrackCb(nowPlaying);
      }
    },
    next() {
      if (mode === 'files' && !switching) playIndex(index + 1);
      else if (mode === 'youtube') getYt().next();
    },
    setVolume(v) {
      master.gain.value = v;
      yt?.setVolume(v);
    },
    update(dt) {
      if (mode === 'youtube') {
        // YouTube sesi analiz edilemez: ayarlardaki sabit tempo
        const prev = beat.phase;
        beat.phase += ((yt?.playing ? ytBpm : 60) / 60) * dt;
        if (yt?.playing && Math.floor(beat.phase) !== Math.floor(prev)) beat.pulse = 1;
      } else if (mode === 'synth') {
        // üretilen ritimde vuruş zamanı tam bilinir
        const p = synth.phase();
        if (Math.floor(p) !== Math.floor(beat.phase)) beat.pulse = 1;
        beat.phase = p;
      } else if (mode === 'files') {
        detect(dt);
        const el = current?.el;
        if (el && !switching && el.duration && el.duration - el.currentTime < crossfade && tracks.length) {
          playIndex(index + 1);
        }
      } else {
        beat.phase += 2 * dt;
      }
      beat.pulse = Math.max(0, beat.pulse - dt * 4);
      return beat;
    },
  };
  return api;
}

Lisans bilgisi projenin LICENSE dosyasında.