Adiciona site de loops
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
aa05552170
commit
5f5850fd02
45 files changed
+1281
No files matched your search
@@ -0,0 +1,159 @@
|
||||
(() => {
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const { loops, comandos } = window.loopsMixer;
|
||||
|
||||
/* Abas */
|
||||
const abas = [['aba-loops', 'painel-loops'], ['aba-joystick', 'painel-joystick']];
|
||||
abas.forEach(([aba]) => $(aba).addEventListener('click', () => {
|
||||
abas.forEach(([a, p]) => {
|
||||
$(a).setAttribute('aria-selected', a === aba);
|
||||
$(p).hidden = a !== aba;
|
||||
});
|
||||
}));
|
||||
|
||||
const CONTROLES = [
|
||||
['transporte', 'Tocar ou pausar', () => comandos.transporte()],
|
||||
['adiantar', 'Adiantar 4 tempos', () => comandos.saltar(4)],
|
||||
['voltar', 'Voltar 4 tempos', () => comandos.saltar(-4)],
|
||||
['mais', 'Aumentar andamento', () => comandos.andamento(1)],
|
||||
['menos', 'Diminuir andamento', () => comandos.andamento(-1)],
|
||||
['bip', 'Ligar ou desligar o bip', () => comandos.bip()],
|
||||
];
|
||||
|
||||
// Nomes do layout padrão de controles, na ordem da Gamepad API.
|
||||
const NOMES = ['A', 'B', 'X', 'Y', 'LB', 'RB', 'LT', 'RT', 'Select', 'Start', 'L3', 'R3', 'Cima', 'Baixo', 'Esq.', 'Dir.', 'Home'];
|
||||
const RITMOS = [...new Set(loops.map((l) => l.ritmo))];
|
||||
const TEXTO_VAZIO = 'Conecte o joystick e aperte qualquer botão dele. O navegador só mostra o controle depois do primeiro botão.';
|
||||
|
||||
// Cada joystick começa com um ritmo: o 1 com o primeiro, o 2 com o segundo...
|
||||
function mapaPadrao(pad, posicao) {
|
||||
if (pad.mapping !== 'standard') return {};
|
||||
const doRitmo = loops.filter((l) => l.ritmo === RITMOS[posicao % RITMOS.length]);
|
||||
const mapa = { 8: 'bip', 9: 'transporte', 12: 'mais', 13: 'menos', 14: 'voltar', 15: 'adiantar' };
|
||||
[0, 1, 2, 3, 4, 5].forEach((botao, i) => {
|
||||
if (doRitmo[i]) mapa[botao] = `loop:${doRitmo[i].id}`;
|
||||
});
|
||||
return mapa;
|
||||
}
|
||||
|
||||
function ler(chave) {
|
||||
try { return JSON.parse(localStorage.getItem(chave)); } catch (e) { return null; }
|
||||
}
|
||||
|
||||
function gravar(chave, valor) {
|
||||
try { localStorage.setItem(chave, JSON.stringify(valor)); } catch (e) { /* segue sem salvar */ }
|
||||
}
|
||||
|
||||
function montarOpcoes(select) {
|
||||
select.add(new Option('Sem função', ''));
|
||||
const controles = document.createElement('optgroup');
|
||||
controles.label = 'Controles';
|
||||
CONTROLES.forEach(([v, nome]) => controles.append(new Option(nome, v)));
|
||||
select.append(controles);
|
||||
RITMOS.forEach((ritmo) => {
|
||||
const g = document.createElement('optgroup');
|
||||
g.label = ritmo;
|
||||
loops.filter((l) => l.ritmo === ritmo).forEach((l) => g.append(new Option(l.nome, `loop:${l.id}`)));
|
||||
select.append(g);
|
||||
});
|
||||
}
|
||||
|
||||
function montarControle(pad, posicao) {
|
||||
// Modelos iguais têm o mesmo id; a vaga separa as configurações.
|
||||
const chave = `loops-joystick:${pad.id}:${posicao}`;
|
||||
const padrao = mapaPadrao(pad, posicao);
|
||||
const controle = {
|
||||
index: pad.index,
|
||||
mapa: ler(chave) || { ...padrao },
|
||||
anteriores: pad.buttons.map((b) => b.pressed), // quem já estava apertado não dispara
|
||||
};
|
||||
|
||||
const painel = document.createElement('section');
|
||||
painel.className = 'joy-painel';
|
||||
const titulo = document.createElement('h3');
|
||||
titulo.textContent = `Joystick ${posicao + 1}: ${pad.id.split('(')[0].trim() || 'sem nome'}`;
|
||||
const lista = document.createElement('div');
|
||||
lista.className = 'joy-botoes';
|
||||
const nomes = pad.mapping === 'standard' ? NOMES : [];
|
||||
|
||||
controle.linhas = pad.buttons.map((_, i) => {
|
||||
const nome = nomes[i] || String(i + 1);
|
||||
const linha = document.createElement('div');
|
||||
linha.className = 'joy-linha';
|
||||
const tecla = document.createElement('span');
|
||||
tecla.className = 'joy-tecla';
|
||||
tecla.textContent = nome;
|
||||
const select = document.createElement('select');
|
||||
select.setAttribute('aria-label', `Joystick ${posicao + 1}, função do botão ${nome}`);
|
||||
montarOpcoes(select);
|
||||
select.value = controle.mapa[i] || '';
|
||||
select.addEventListener('change', () => {
|
||||
controle.mapa[i] = select.value;
|
||||
gravar(chave, controle.mapa);
|
||||
});
|
||||
linha.append(tecla, select);
|
||||
lista.append(linha);
|
||||
return { tecla, select };
|
||||
});
|
||||
|
||||
const restaurar = document.createElement('button');
|
||||
restaurar.type = 'button';
|
||||
restaurar.className = 'tap';
|
||||
restaurar.textContent = 'Voltar ao padrão';
|
||||
restaurar.addEventListener('click', () => {
|
||||
controle.mapa = { ...padrao };
|
||||
gravar(chave, controle.mapa);
|
||||
controle.linhas.forEach((l, i) => { l.select.value = controle.mapa[i] || ''; });
|
||||
});
|
||||
|
||||
painel.append(titulo, lista, restaurar);
|
||||
$('joy-paineis').append(painel);
|
||||
return controle;
|
||||
}
|
||||
|
||||
let assinatura = '';
|
||||
let controles = [];
|
||||
|
||||
function remontar(pads) {
|
||||
$('joy-paineis').replaceChildren();
|
||||
// A vaga do navegador não muda se outro joystick sair.
|
||||
controles = pads.map((pad) => montarControle(pad, pad.index));
|
||||
if (!pads.length) {
|
||||
$('joy-nome').textContent = 'Nenhum joystick encontrado';
|
||||
$('joy-status').textContent = TEXTO_VAZIO;
|
||||
} else {
|
||||
$('joy-nome').textContent = pads.length === 1 ? '1 joystick conectado' : `${pads.length} joysticks conectados`;
|
||||
$('joy-status').textContent = 'Aperte um botão para ver qual é. Depois escolha o que ele faz. Todos controlam a mesma música.';
|
||||
}
|
||||
}
|
||||
|
||||
function executar(valor) {
|
||||
if (!valor) return;
|
||||
if (valor.startsWith('loop:')) {
|
||||
comandos.loop(valor.slice(5));
|
||||
return;
|
||||
}
|
||||
const acao = CONTROLES.find(([v]) => v === valor);
|
||||
if (acao) acao[2]();
|
||||
}
|
||||
|
||||
function lerControles() {
|
||||
const pads = navigator.getGamepads ? [...navigator.getGamepads()].filter(Boolean) : [];
|
||||
const atual = pads.map((p) => `${p.index}|${p.id}|${p.buttons.length}`).join('\n');
|
||||
if (atual !== assinatura) {
|
||||
assinatura = atual;
|
||||
remontar(pads);
|
||||
}
|
||||
pads.forEach((pad, p) => {
|
||||
const controle = controles[p];
|
||||
pad.buttons.forEach((b, i) => {
|
||||
controle.linhas[i].tecla.classList.toggle('apertado', b.pressed);
|
||||
if (b.pressed && !controle.anteriores[i]) executar(controle.mapa[i]);
|
||||
controle.anteriores[i] = b.pressed;
|
||||
});
|
||||
});
|
||||
requestAnimationFrame(lerControles);
|
||||
}
|
||||
|
||||
requestAnimationFrame(lerControles);
|
||||
})();
|
||||
@@ -0,0 +1,475 @@
|
||||
(() => {
|
||||
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),
|
||||
},
|
||||
};
|
||||
})();
|
||||
Reference in new issue
Block a user