v1.0.13 - botao de reset funcional para limpar as salas

This commit is contained in:
JotaChina committed 2025-11-15 15:36:39 -03:00
1 parent 611aec9ba1
commit c8323d56cf
9 files changed
+1593 -532

No files matched your search

+155 -73
View File
@@ -1,7 +1,15 @@
// js/audio/audio_audio.js
import { appState } from "../state.js";
import { updateAudioEditorUI, updatePlayheadVisual, resetPlayheadVisual } from "./audio_ui.js";
import { initializeAudioContext, getAudioContext, getMainGainNode } from "../audio.js";
import {
updateAudioEditorUI,
updatePlayheadVisual,
resetPlayheadVisual,
} from "./audio_ui.js";
import {
initializeAudioContext,
getAudioContext,
getMainGainNode,
} from "../audio.js";
import { getPixelsPerSecond } from "../utils.js";
// 🔊 ADIÇÃO: usar a MESMA instância do Tone que o projeto usa
import * as Tone from "https://esm.sh/tone";
@@ -17,19 +25,19 @@ let schedulerIntervalId = null;
let animationFrameId = null;
// Sincronização de Tempo
let startTime = 0;
let startTime = 0;
// (seek/logical ficam em appState.audio)
// Configurações de Loop
let isLoopActive = false;
let loopStartTimeSec = 0;
let loopEndTimeSec = 8;
let loopEndTimeSec = 8;
// estado runtime
const runtimeClipState = new Map();
// ⚠️ agora armazenamos Tone.Player em vez de BufferSource
const scheduledNodes = new Map(); // eventId -> { player, clipId }
let nextEventId = 0;
let nextEventId = 0;
const callbacks = {
onClipScheduled: null,
@@ -41,9 +49,15 @@ function _getBpm() {
const bpmInput = document.getElementById("bpm-input");
return parseFloat(bpmInput.value) || 120;
}
function _getSecondsPerBeat() { return 60.0 / _getBpm(); }
function _convertBeatToSeconds(beat) { return beat * _getSecondsPerBeat(); }
function _convertSecondsToBeat(seconds) { return seconds / _getSecondsPerBeat(); }
function _getSecondsPerBeat() {
return 60.0 / _getBpm();
}
function _convertBeatToSeconds(beat) {
return beat * _getSecondsPerBeat();
}
function _convertSecondsToBeat(seconds) {
return seconds / _getSecondsPerBeat();
}
// garante um único contexto — o rawContext do Tone
function _initContext() {
@@ -75,8 +89,14 @@ function _scheduleClip(clip, absolutePlayTime, durationSec) {
if (!toneBuf) return;
// cadeia de ganho/pan por clipe (se já tiver no estado, use; aqui garantimos)
const gain = clip.gainNode instanceof Tone.Gain ? clip.gainNode : new Tone.Gain(clip.volume ?? 1);
const pan = clip.pannerNode instanceof Tone.Panner ? clip.pannerNode : new Tone.Panner(clip.pan ?? 0);
const gain =
clip.gainNode instanceof Tone.Gain
? clip.gainNode
: new Tone.Gain(clip.volume ?? 1);
const pan =
clip.pannerNode instanceof Tone.Panner
? clip.pannerNode
: new Tone.Panner(clip.pan ?? 0);
// conecta no destino principal (é um ToneAudioNode)
try {
@@ -91,19 +111,35 @@ function _scheduleClip(clip, absolutePlayTime, durationSec) {
const player = new Tone.Player(toneBuf).sync().connect(gain);
// aplica pitch como rate (semitons → rate)
const rate = (clip.pitch && clip.pitch !== 0) ? Math.pow(2, clip.pitch / 12) : 1;
const rate =
clip.pitch && clip.pitch !== 0 ? Math.pow(2, clip.pitch / 12) : 1;
player.playbackRate = rate;
// calculamos o "when" no tempo do Transport:
// absolutePlayTime é em audioCtx.currentTime; o "zero" lógico foi quando demos play:
// logical = (now - startTime) + seek; => occurrence = (absolutePlayTime - startTime) + seek
const occurrenceInTransportSec = (absolutePlayTime - startTime) + (appState.audio.audioEditorSeekTime || 0);
const occurrenceInTransportSec =
absolutePlayTime - startTime + (appState.audio.audioEditorSeekTime || 0);
const offset = clip.offsetInSeconds ?? clip.offset ?? 0;
const dur = durationSec ?? toneBuf.duration;
// agenda
player.start(occurrenceInTransportSec, offset, dur);
// --- INÍCIO DA CORREÇÃO (BUG: RangeError) ---
// O log de erro (RangeError: Value must be within [0, Infinity])
// indica que um destes valores é um número negativo minúsculo
// (um bug de precisão de ponto flutuante).
// Usamos Math.max(0, ...) para "clampar" os valores e garantir
// que nunca sejam negativos.
const safeOccurrence = Math.max(0, occurrenceInTransportSec);
const safeOffset = Math.max(0, offset);
// Duração pode ser 'undefined', mas se existir, não pode ser negativa
const safeDur =
dur === undefined || dur === null ? undefined : Math.max(0, dur);
// --- FIM DA CORREÇÃO ---
// agenda (agora usando os valores seguros)
player.start(safeOccurrence, safeOffset, safeDur);
const eventId = nextEventId++;
scheduledNodes.set(eventId, { player, clipId: clip.id });
@@ -115,17 +151,21 @@ function _scheduleClip(clip, absolutePlayTime, durationSec) {
// quando parar naturalmente, limpamos runtime
player.onstop = () => {
_handleClipEnd(eventId, clip.id);
try { player.unsync(); } catch {}
try { player.dispose(); } catch {}
try {
player.unsync();
} catch {}
try {
player.dispose();
} catch {}
};
}
function _handleClipEnd(eventId, clipId) {
scheduledNodes.delete(eventId);
runtimeClipState.delete(clipId);
runtimeClipState.delete(clipId);
if (callbacks.onClipPlayed) {
const clip = appState.audio.clips.find(c => c.id == clipId);
const clip = appState.audio.clips.find((c) => c.id == clipId);
if (clip) callbacks.onClipPlayed(clip);
}
}
@@ -134,7 +174,8 @@ function _schedulerTick() {
if (!isPlaying || !audioCtx) return;
const now = audioCtx.currentTime;
const logicalTime = (now - startTime) + (appState.audio.audioEditorSeekTime || 0);
const logicalTime =
now - startTime + (appState.audio.audioEditorSeekTime || 0);
const scheduleWindowStartSec = logicalTime;
const scheduleWindowEndSec = logicalTime + SCHEDULE_AHEAD_TIME_SEC;
@@ -145,19 +186,32 @@ function _schedulerTick() {
const clipStartTimeSec = clip.startTimeInSeconds;
const clipDurationSec = clip.durationInSeconds;
if (typeof clipStartTimeSec === 'undefined' || typeof clipDurationSec === 'undefined') continue;
if (
typeof clipStartTimeSec === "undefined" ||
typeof clipDurationSec === "undefined"
)
continue;
let occurrenceStartTimeSec = clipStartTimeSec;
if (isLoopActive) {
const loopDuration = loopEndTimeSec - loopStartTimeSec;
if (loopDuration <= 0) continue;
if (occurrenceStartTimeSec < loopStartTimeSec && logicalTime >= loopStartTimeSec) {
const offsetFromLoopStart = (occurrenceStartTimeSec - loopStartTimeSec) % loopDuration;
occurrenceStartTimeSec = loopStartTimeSec + (offsetFromLoopStart < 0 ? offsetFromLoopStart + loopDuration : offsetFromLoopStart);
if (loopDuration <= 0) continue;
if (
occurrenceStartTimeSec < loopStartTimeSec &&
logicalTime >= loopStartTimeSec
) {
const offsetFromLoopStart =
(occurrenceStartTimeSec - loopStartTimeSec) % loopDuration;
occurrenceStartTimeSec =
loopStartTimeSec +
(offsetFromLoopStart < 0
? offsetFromLoopStart + loopDuration
: offsetFromLoopStart);
}
if (occurrenceStartTimeSec < logicalTime) {
const loopsMissed = Math.floor((logicalTime - occurrenceStartTimeSec) / loopDuration) + 1;
const loopsMissed =
Math.floor((logicalTime - occurrenceStartTimeSec) / loopDuration) + 1;
occurrenceStartTimeSec += loopsMissed * loopDuration;
}
}
@@ -166,7 +220,9 @@ function _schedulerTick() {
occurrenceStartTimeSec >= scheduleWindowStartSec &&
occurrenceStartTimeSec < scheduleWindowEndSec
) {
const absolutePlayTime = startTime + (occurrenceStartTimeSec - (appState.audio.audioEditorSeekTime || 0));
const absolutePlayTime =
startTime +
(occurrenceStartTimeSec - (appState.audio.audioEditorSeekTime || 0));
_scheduleClip(clip, absolutePlayTime, clipDurationSec);
clipRuntime.isScheduled = true;
runtimeClipState.set(clip.id, clipRuntime);
@@ -181,31 +237,33 @@ function _animationLoop() {
return;
}
const now = audioCtx.currentTime;
let newLogicalTime = (now - startTime) + (appState.audio.audioEditorSeekTime || 0);
let newLogicalTime =
now - startTime + (appState.audio.audioEditorSeekTime || 0);
if (isLoopActive) {
if (newLogicalTime >= loopEndTimeSec) {
const loopDuration = loopEndTimeSec - loopStartTimeSec;
newLogicalTime = loopStartTimeSec + ((newLogicalTime - loopStartTimeSec) % loopDuration);
newLogicalTime =
loopStartTimeSec + ((newLogicalTime - loopStartTimeSec) % loopDuration);
startTime = now;
appState.audio.audioEditorSeekTime = newLogicalTime;
}
}
appState.audio.audioEditorLogicalTime = newLogicalTime;
appState.audio.audioEditorLogicalTime = newLogicalTime;
if (!isLoopActive) {
let maxTime = 0;
appState.audio.clips.forEach(clip => {
const clipStartTime = clip.startTimeInSeconds || 0;
const clipDuration = clip.durationInSeconds || 0;
const endTime = clipStartTime + clipDuration;
if (endTime > maxTime) maxTime = endTime;
appState.audio.clips.forEach((clip) => {
const clipStartTime = clip.startTimeInSeconds || 0;
const clipDuration = clip.durationInSeconds || 0;
const endTime = clipStartTime + clipDuration;
if (endTime > maxTime) maxTime = endTime;
});
if (maxTime > 0 && appState.audio.audioEditorLogicalTime >= maxTime) {
stopAudioEditorPlayback(true); // Rebobina no fim
resetPlayheadVisual();
return;
stopAudioEditorPlayback(true); // Rebobina no fim
resetPlayheadVisual();
return;
}
}
const pixelsPerSecond = getPixelsPerSecond();
@@ -222,23 +280,30 @@ export function updateTransportLoop() {
loopEndTimeSec = appState.global.loopEndTime;
runtimeClipState.clear();
// parar e descartar players agendados
scheduledNodes.forEach(({ player }) => {
try { player.unsync(); } catch {}
try { player.stop(); } catch {}
try { player.dispose(); } catch {}
try {
player.unsync();
} catch {}
try {
player.stop();
} catch {}
try {
player.dispose();
} catch {}
});
scheduledNodes.clear();
}
export async function startAudioEditorPlayback(seekTime) { // 1. Aceita 'seekTime' como parâmetro
export async function startAudioEditorPlayback(seekTime) {
// 1. Aceita 'seekTime' como parâmetro
if (isPlaying) return;
_initContext();
// garante contexto ativo do Tone (gesto do usuário já ocorreu antes)
await Tone.start();
if (audioCtx.state === 'suspended') {
if (audioCtx.state === "suspended") {
await audioCtx.resume();
}
@@ -251,23 +316,24 @@ export async function startAudioEditorPlayback(seekTime) { // 1. Aceita 'seekTim
// =================================================================
// 👇 INÍCIO DA CORREÇÃO (Bugs 1 & 2)
// =================================================================
// 1. Determine o tempo de início:
// Use o 'seekTime' recebido (da ação global) se for um número válido (>= 0).
// Caso contrário, use o tempo de seek local atual.
const timeToStart = (seekTime !== null && seekTime !== undefined && !isNaN(seekTime))
? seekTime
: (appState.audio.audioEditorSeekTime || 0); // 👈 Usa sua variável de estado
let timeToStart =
seekTime !== null && seekTime !== undefined && !isNaN(seekTime)
? seekTime
: appState.audio.audioEditorSeekTime || 0; // 👈 Usa sua variável de estado
// 2. Atualize o estado global (para a agulha pular)
// Isso garante que o estado local E o Tone estejam sincronizados.
appState.audio.audioEditorSeekTime = timeToStart;
// 2. Clampa o valor (parte da correção do RangeError)
timeToStart = Math.max(0, timeToStart);
// 3. Alinhe o Tone.Transport a esse tempo
// 3. Atualize o estado global (para a agulha pular)
appState.audio.audioEditorSeekTime = timeToStart;
// 4. Alinhe o Tone.Transport a esse tempo
try {
Tone.Transport.seconds = timeToStart; // 👈 Usa o tempo sincronizado
} catch {}
// =================================================================
// 👆 FIM DA CORREÇÃO
// =================================================================
@@ -295,37 +361,48 @@ export function stopAudioEditorPlayback(rewind = false) {
isPlaying = false;
appState.global.isAudioEditorPlaying = false;
console.log(`%cParando Playback... (Rewind: ${rewind})`, "color: #d9534f;");
// para o Transport (para Players .sync())
try { Tone.Transport.stop(); } catch {}
try {
Tone.Transport.stop();
} catch {}
clearInterval(schedulerIntervalId);
schedulerIntervalId = null;
cancelAnimationFrame(animationFrameId);
animationFrameId = null;
appState.audio.audioEditorSeekTime = appState.audio.audioEditorLogicalTime || 0;
appState.audio.audioEditorLogicalTime = 0;
appState.audio.audioEditorSeekTime =
appState.audio.audioEditorLogicalTime || 0;
appState.audio.audioEditorLogicalTime = 0;
if (rewind) {
appState.audio.audioEditorSeekTime = 0;
try { Tone.Transport.seconds = 0; } catch {}
try {
Tone.Transport.seconds = 0;
} catch {}
}
// parar e descartar players agendados
scheduledNodes.forEach(({ player }) => {
try { player.unsync(); } catch {}
try { player.stop(); } catch {}
try { player.dispose(); } catch {}
try {
player.unsync();
} catch {}
try {
player.stop();
} catch {}
try {
player.dispose();
} catch {}
});
scheduledNodes.clear();
runtimeClipState.clear();
updateAudioEditorUI();
const playBtn = document.getElementById("audio-editor-play-btn");
if (playBtn) playBtn.className = 'fa-solid fa-play';
if (playBtn) playBtn.className = "fa-solid fa-play";
if (rewind) {
resetPlayheadVisual();
}
@@ -343,16 +420,21 @@ export function seekAudioEditor(newTime) {
if (wasPlaying) {
stopAudioEditorPlayback(false); // Pausa
}
// Clampa o novo tempo
newTime = Math.max(0, newTime);
appState.audio.audioEditorSeekTime = newTime;
appState.audio.audioEditorLogicalTime = newTime;
try { Tone.Transport.seconds = newTime; } catch {}
appState.audio.audioEditorLogicalTime = newTime;
try {
Tone.Transport.seconds = newTime;
} catch {}
const pixelsPerSecond = getPixelsPerSecond();
const newPositionPx = newTime * pixelsPerSecond;
updatePlayheadVisual(newPositionPx);
if (wasPlaying) {
startAudioEditorPlayback();
}