(() => { const $ = (id) => document.getElementById(id); const base = document.querySelector('.mixer').dataset.base || ''; const grupos = JSON.parse($('loops-dados').textContent); const TECLAS = '1234567890qwertyuiopasd'; const ctx = new (window.AudioContext || window.webkitAudioContext)(); const limitador = ctx.createDynamicsCompressor(); limitador.threshold.value = -3; limitador.ratio.value = 12; limitador.attack.value = 0.003; const geral = ctx.createGain(); geral.gain.value = Number($('volume-geral').value); geral.connect(limitador).connect(ctx.destination); const loops = grupos.flatMap((g) => g.loops.map((l) => ({ ...l, ritmo: g.ritmo, disparo: Boolean(g.disparo), url: encodeURI(`${base}/assets/audio/${g.pasta}/${l.arquivo}`), disco: document.querySelector(`.disco[data-id="${l.id}"]`), selecionado: false, voz: null, cache: new Map(), }))); // O bip toca como um loop de 4 tempos: pausa, salta e muda de andamento junto. const bip = { id: 'bip', bip: true, tempos: 4, selecionado: false, voz: null, cache: new Map(), saida: ctx.createGain(), }; bip.saida.gain.value = Number($('volume-bip').value); bip.saida.connect(geral); const vozes = [...loops, bip]; const mdc = (a, b) => (b ? mdc(b, a % b) : a); const CICLO = loops.filter((l) => !l.disparo).reduce((a, l) => (a * l.tempos) / mdc(a, l.tempos), 4); const emCiclo = (b, c = CICLO) => ((b % c) + c) % c; let tocando = false; let bpm = 100; let posicao = 0; let ancoraTempo = 0; let ancoraBatida = 0; let celulaAtual = -1; const batidaEm = (t) => ancoraBatida + ((t - ancoraTempo) * bpm) / 60; const batidaAgora = () => (tocando ? batidaEm(ctx.currentTime) : posicao); function proximaBatida() { const agora = ctx.currentTime + 0.03; return ancoraTempo + ((Math.ceil(batidaEm(agora)) - ancoraBatida) * 60) / bpm; } /* Encontra os ataques de cada golpe, em amostras. */ function acharAtaques(canal, fim, taxa) { const salto = Math.round(taxa * 0.005); const janela = salto * 2; const env = []; for (let i = 0; i + janela < fim; i += salto) { let soma = 0; for (let j = i; j < i + janela; j++) soma += canal[j] * canal[j]; env.push(Math.sqrt(soma / janela)); } const maximo = env.reduce((a, b) => Math.max(a, b), 0); const fluxo = env.slice(1).map((v, i) => Math.max(0, Math.log(v + 1e-3) - Math.log(env[i] + 1e-3))); const media = fluxo.reduce((a, b) => a + b, 0) / fluxo.length; const desvio = Math.sqrt(fluxo.reduce((a, b) => a + (b - media) ** 2, 0) / fluxo.length); const limiar = Math.max(0.35, media + 1.5 * desvio); const distancia = Math.round(taxa * 0.06); const ataques = [0]; for (let i = 1; i < fluxo.length - 1; i++) { const forte = env[Math.min(i + 4, env.length - 1)] > 0.04 * maximo; if (fluxo[i] > limiar && fluxo[i] >= fluxo[i - 1] && fluxo[i] >= fluxo[i + 1] && forte) { const pos = Math.max(0, i * salto - Math.round(taxa * 0.003)); if (pos - ataques[ataques.length - 1] > distancia) ataques.push(pos); } } return ataques; } function criarBip(novoBpm) { const taxa = ctx.sampleRate; const total = Math.round((4 * 60 * taxa) / novoBpm); const saida = ctx.createBuffer(1, total, taxa); const dados = saida.getChannelData(0); const n = Math.round(taxa * 0.05); for (let b = 0; b < 4; b++) { const inicio = Math.round((b * total) / 4); const freq = b === 0 ? 1568 : 1047; for (let i = 0; i < n; i++) { const t = i / taxa; dados[inicio + i] = Math.sin(2 * Math.PI * freq * t) * Math.exp(-t * 90) * Math.min(1, i / 40); } } return saida; } /* Muda o andamento sem mudar o tom: cada golpe vai para o novo lugar. */ function criarBuffer(l, novoBpm) { const { original, fim, ataques, tempos } = l; const taxa = original.sampleRate; const total = Math.round((tempos * 60 * taxa) / novoBpm); const razao = total / fim; const saida = ctx.createBuffer(original.numberOfChannels, total, taxa); const queda = Math.round(taxa * 0.006); for (let c = 0; c < original.numberOfChannels; c++) { const de = original.getChannelData(c); const para = saida.getChannelData(c); ataques.forEach((inicio, k) => { const proximo = k + 1 < ataques.length ? ataques[k + 1] : fim; const destino = Math.round(inicio * razao); const vaga = Math.min(total, Math.round(proximo * razao)) - destino; const n = Math.min(proximo - inicio, vaga); for (let i = 0; i < n; i++) { const f = n - i <= queda ? (n - i) / queda : 1; para[destino + i] = de[inicio + i] * f; } }); } return saida; } function renderizar(l, novoBpm) { if (l.cache.has(novoBpm)) return l.cache.get(novoBpm); const buffer = l.bip ? criarBip(novoBpm) : criarBuffer(l, novoBpm); if (l.cache.size >= 3) l.cache.clear(); l.cache.set(novoBpm, buffer); return buffer; } function iniciarVoz(l, quando, suave) { const src = ctx.createBufferSource(); src.buffer = renderizar(l, bpm); src.loop = true; const ganho = ctx.createGain(); if (suave) { ganho.gain.setValueAtTime(0, quando); ganho.gain.linearRampToValueAtTime(1, quando + 0.02); } src.connect(ganho).connect(l.saida); src.start(quando, (emCiclo(batidaEm(quando), l.tempos) * 60) / bpm); l.voz = { src, ganho }; } function pararVoz(l, quando) { if (!l.voz) return; const { src, ganho } = l.voz; ganho.gain.setValueAtTime(1, quando); ganho.gain.linearRampToValueAtTime(0, quando + 0.02); src.stop(quando + 0.03); l.voz = null; } const prontas = () => vozes.filter((l) => l.selecionado && (l.bip || l.original)); function reiniciarVozes(quando) { vozes.filter((l) => l.voz).forEach((l) => { pararVoz(l, quando); iniciarVoz(l, quando, true); }); } /* Andamento */ let espera = 0; function mudarBpm(valor) { const novo = Math.min(200, Math.max(50, Math.round(valor))); $('bpm-valor').textContent = novo; $('bpm').value = novo; clearTimeout(espera); espera = setTimeout(() => aplicarBpm(novo), tocando ? 90 : 0); } function aplicarBpm(novo) { if (novo === bpm) return; if (!tocando) { bpm = novo; return; } vozes.filter((l) => l.voz).forEach((l) => renderizar(l, novo)); const quando = ctx.currentTime + 0.05; ancoraBatida = batidaEm(quando); ancoraTempo = quando; bpm = novo; reiniciarVozes(quando); } /* Transporte */ function atualizarStatus() { const n = loops.filter((l) => l.selecionado).length; let texto; if (tocando) texto = n ? 'Tocando. Ligue ou desligue loops: eles entram na próxima batida.' : 'Nenhum loop ligado. Toque em um disco.'; else if (n) texto = `Aperte Tocar para começar no tempo ${Math.floor(emCiclo(posicao)) + 1}.`; else texto = 'Escolha os loops nos discos e aperte Tocar.'; $('status').textContent = texto; } function alternarTransporte() { const botao = $('tocar'); if (botao.disabled) return; if (tocando) { const quando = ctx.currentTime + 0.005; posicao = emCiclo(batidaEm(quando)); vozes.forEach((l) => pararVoz(l, quando)); calarSinos(quando); tocando = false; botao.textContent = 'Tocar'; botao.setAttribute('aria-pressed', 'false'); } else { ctx.resume(); ancoraTempo = ctx.currentTime + 0.08; ancoraBatida = posicao; tocando = true; prontas().forEach((l) => iniciarVoz(l, ancoraTempo, true)); botao.textContent = 'Pausar'; botao.setAttribute('aria-pressed', 'true'); requestAnimationFrame(animar); // O navegador só libera som depois de um clique ou tecla na página. setTimeout(() => { if (tocando && ctx.state !== 'running') $('status').textContent = 'Clique uma vez na página para liberar o som.'; }, 400); } pintar(); atualizarStatus(); } function irPara(batida) { if (!tocando) { posicao = batida; pintar(); atualizarStatus(); return; } const quando = proximaBatida(); ancoraBatida = batida; ancoraTempo = quando; reiniciarVozes(quando); } function saltar(tempos) { const agora = batidaAgora(); irPara(emCiclo((tocando ? Math.ceil(agora) : Math.floor(agora)) + tempos)); } /* Sinos: entram na próxima batida e soam até o fim, sem mudar de andamento. */ const sinosSoando = new Set(); function animarSinos() { sinosSoando.forEach((s) => { const p = Math.min(1, Math.max(0, (ctx.currentTime - s.inicio) / s.src.buffer.duration)); if (s.l.soando === s) s.l.disco.style.setProperty('--p', `${p * 360}deg`); }); if (sinosSoando.size) requestAnimationFrame(animarSinos); } function dispararSino(l) { ctx.resume(); const inicio = tocando ? proximaBatida() : ctx.currentTime + 0.01; const src = ctx.createBufferSource(); src.buffer = l.original; const ganho = ctx.createGain(); src.connect(ganho).connect(l.saida); src.start(inicio); const s = { l, src, ganho, inicio }; src.onended = () => { sinosSoando.delete(s); if (l.soando === s) { l.soando = null; l.disco.classList.remove('soando'); } }; l.soando = s; l.disco.classList.add('soando'); sinosSoando.add(s); if (sinosSoando.size === 1) requestAnimationFrame(animarSinos); } function calarSinos(quando) { sinosSoando.forEach(({ src, ganho }) => { ganho.gain.setValueAtTime(1, quando); ganho.gain.linearRampToValueAtTime(0, quando + 0.05); src.stop(quando + 0.06); }); } function alternar(l) { if (l.disco && l.disco.disabled) return; if (l.disparo) { dispararSino(l); return; } l.selecionado = !l.selecionado; (l.disco || $('bip')).setAttribute('aria-pressed', l.selecionado); if (tocando) { const quando = l.bip ? ctx.currentTime + 0.02 : proximaBatida(); if (l.selecionado) iniciarVoz(l, quando, true); else pararVoz(l, quando); } pintar(); atualizarStatus(); } /* Desenho */ const celulas = Array.from({ length: CICLO }, (_, i) => { const b = document.createElement('button'); b.type = 'button'; b.textContent = i + 1; b.setAttribute('aria-label', `Tempo ${i + 1}`); if (i % 4 === 0) b.classList.add('forte'); b.addEventListener('click', () => irPara(i)); $('inicio').append(b); return b; }); function pintar() { const batida = Math.max(0, emCiclo(batidaAgora())); const celula = Math.floor(batida); if (celula !== celulaAtual) { if (celulaAtual >= 0) celulas[celulaAtual].classList.remove('atual'); celulas[celula].classList.add('atual'); celulaAtual = celula; } loops.forEach((l) => { if (l.selecionado) l.disco.style.setProperty('--p', `${(emCiclo(batida, l.tempos) / l.tempos) * 360}deg`); }); } function animar() { if (!tocando) return; pintar(); requestAnimationFrame(animar); } function criarSvg(classe, d, pontos) { const NS = 'http://www.w3.org/2000/svg'; const svg = document.createElementNS(NS, 'svg'); svg.setAttribute('viewBox', '-100 -100 200 200'); svg.setAttribute('aria-hidden', 'true'); svg.setAttribute('class', classe); const barras = document.createElementNS(NS, 'path'); barras.setAttribute('class', 'barras'); barras.setAttribute('d', d); svg.append(barras); if (pontos) svg.append(pontos); return svg; } /* Desenha a onda real do áudio como barras em volta do disco. */ function desenharDisco(l) { const NS = 'http://www.w3.org/2000/svg'; const canal = l.original.getChannelData(0); const partes = 84; const picos = Array.from({ length: partes }, (_, i) => { const a = Math.floor((i / partes) * l.fim); const b = Math.floor(((i + 1) / partes) * l.fim); let soma = 0; let qtd = 0; for (let j = a; j < b; j += 8) { soma += canal[j] * canal[j]; qtd++; } return Math.sqrt(soma / qtd); }); const maior = picos.reduce((a, b) => Math.max(a, b), 0) || 1; const xy = (r, ang) => `${(r * Math.sin(ang)).toFixed(1)} ${(-r * Math.cos(ang)).toFixed(1)}`; let d = ''; picos.forEach((p, i) => { const ang = ((i + 0.5) / partes) * 2 * Math.PI; const h = 1.5 + 19 * Math.sqrt(p / maior); d += `M${xy(73 - h, ang)}L${xy(73 + h, ang)}`; }); const pontos = document.createElementNS(NS, 'g'); pontos.setAttribute('class', 'pontos'); for (let i = 0; i < l.tempos; i++) { const ang = (i / l.tempos) * 2 * Math.PI; const c = document.createElementNS(NS, 'circle'); c.setAttribute('cx', (97 * Math.sin(ang)).toFixed(1)); c.setAttribute('cy', (-97 * Math.cos(ang)).toFixed(1)); c.setAttribute('r', i === 0 ? 3 : 1.6); pontos.append(c); } l.disco.prepend(criarSvg('base', d, pontos), criarSvg('aceso', d)); } async function carregar(l) { const r = await fetch(l.url); if (!r.ok) throw new Error(`HTTP ${r.status}`); l.original = await ctx.decodeAudioData(await r.arrayBuffer()); const taxa = l.original.sampleRate; l.fim = l.ate ? Math.min(Math.round(l.ate * taxa), l.original.length) : l.original.length; if (!l.disparo) l.ataques = acharAtaques(l.original.getChannelData(0), l.fim, taxa); l.saida = ctx.createGain(); l.saida.gain.value = l.volume; l.saida.connect(geral); desenharDisco(l); l.disco.disabled = false; } /* Controles */ loops.forEach((l) => { l.disco.addEventListener('click', () => alternar(l)); document.querySelector(`[data-volume="${l.id}"]`).addEventListener('input', (e) => { l.volume = Number(e.target.value); if (l.saida) l.saida.gain.setTargetAtTime(l.volume, ctx.currentTime, 0.01); }); }); $('tocar').addEventListener('click', alternarTransporte); $('bip').addEventListener('click', () => alternar(bip)); $('volume-bip').addEventListener('input', (e) => { bip.saida.gain.setTargetAtTime(Number(e.target.value), ctx.currentTime, 0.01); }); $('bpm').addEventListener('input', (e) => mudarBpm(Number(e.target.value))); $('bpm-menos').addEventListener('click', () => mudarBpm(Number($('bpm').value) - 1)); $('bpm-mais').addEventListener('click', () => mudarBpm(Number($('bpm').value) + 1)); $('volume-geral').addEventListener('input', (e) => { geral.gain.setTargetAtTime(Number(e.target.value), ctx.currentTime, 0.01); }); let toques = []; $('tap').addEventListener('click', () => { const agora = performance.now(); if (toques.length && agora - toques[toques.length - 1] > 2000) toques = []; toques.push(agora); toques = toques.slice(-5); if (toques.length >= 2) { const media = (toques[toques.length - 1] - toques[0]) / (toques.length - 1); mudarBpm(60000 / media); } }); document.addEventListener('keydown', (e) => { if (e.repeat || e.ctrlKey || e.metaKey || e.altKey || e.target.closest('select')) return; const k = e.key.toLowerCase(); const i = TECLAS.indexOf(k); if (k.length === 1 && i >= 0 && i < loops.length) { alternar(loops[i]); } else if (k === 'b') { alternar(bip); } else if (e.code === 'Space' && !e.target.closest('button, input')) { e.preventDefault(); alternarTransporte(); } }); pintar(); Promise.allSettled(loops.map(carregar)).then((res) => { const falhas = loops.filter((_, i) => res[i].status === 'rejected'); const botao = $('tocar'); if (falhas.length === loops.length) { botao.textContent = 'Sem áudio'; $('status').textContent = 'Os áudios não abriram. Confira se o site está sendo servido pelo _site.'; return; } botao.disabled = false; botao.textContent = 'Tocar'; if (falhas.length) $('status').textContent = `Não abriu: ${falhas.map((l) => l.nome).join(', ')}.`; else atualizarStatus(); }); ['pointerdown', 'keydown'].forEach((ev) => document.addEventListener(ev, () => { if (ctx.state === 'suspended' && tocando) ctx.resume().then(atualizarStatus); })); window.loopsMixer = { loops, bip, renderizar, CICLO, estado: () => ({ tocando, bpm, posicao, batida: batidaAgora() }), comandos: { transporte: alternarTransporte, saltar, bip: () => alternar(bip), loop: (id) => { const l = loops.find((x) => x.id === id); if (l) alternar(l); }, andamento: (d) => mudarBpm(Number($('bpm').value) + d), }, }; })();