sync mode on
This commit is contained in:
1 parent
1818932244
commit
1174b328e5
415 files changed
+44294
-1182
No files matched your search
@@ -1,8 +1,10 @@
|
||||
// js/audio/audio_audio.js
|
||||
import { appState } from "../state.js";
|
||||
import { updateAudioEditorUI, updatePlayheadVisual, resetPlayheadVisual } from "./audio_ui.js";
|
||||
import { initializeAudioContext, getAudioContext } from "../audio.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";
|
||||
|
||||
// --- Configurações do Scheduler ---
|
||||
const LOOKAHEAD_INTERVAL_MS = 25.0;
|
||||
@@ -16,16 +18,17 @@ let animationFrameId = null;
|
||||
|
||||
// Sincronização de Tempo
|
||||
let startTime = 0;
|
||||
let seekTime = 0;
|
||||
let logicalPlaybackTime = 0;
|
||||
// (seek/logical ficam em appState.audio)
|
||||
|
||||
// Configurações de Loop
|
||||
let isLoopActive = false;
|
||||
let loopStartTimeSec = 0;
|
||||
let loopEndTimeSec = 8;
|
||||
|
||||
// estado runtime
|
||||
const runtimeClipState = new Map();
|
||||
const scheduledNodes = new Map();
|
||||
// ⚠️ agora armazenamos Tone.Player em vez de BufferSource
|
||||
const scheduledNodes = new Map(); // eventId -> { player, clipId }
|
||||
let nextEventId = 0;
|
||||
|
||||
const callbacks = {
|
||||
@@ -42,49 +45,78 @@ 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() {
|
||||
if (!audioCtx) {
|
||||
initializeAudioContext();
|
||||
audioCtx = getAudioContext();
|
||||
audioCtx = getAudioContext(); // deve ser o rawContext do Tone
|
||||
}
|
||||
}
|
||||
|
||||
// --- Lógica Principal do Scheduler (sem alterações) ---
|
||||
// helper: normaliza AudioBuffer → ToneAudioBuffer (mesmo contexto)
|
||||
function _toToneBuffer(buffer) {
|
||||
if (!buffer) return null;
|
||||
if (buffer._buffer) return buffer; // já é Tone.ToneAudioBuffer
|
||||
const tab = new Tone.ToneAudioBuffer();
|
||||
tab._buffer = buffer; // injeta o AudioBuffer (já no rawContext do Tone)
|
||||
return tab;
|
||||
}
|
||||
|
||||
// --- Lógica Principal do Scheduler (mantida) ---
|
||||
|
||||
function _scheduleClip(clip, absolutePlayTime, durationSec) {
|
||||
if (!clip.buffer) {
|
||||
console.warn(`Clip ${clip.id} não possui áudio buffer carregado.`);
|
||||
return;
|
||||
}
|
||||
if (!clip.gainNode || !clip.pannerNode) {
|
||||
console.warn(`Clip ${clip.id} não possui gainNode ou pannerNode.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const source = new Tone.BufferSource(clip.buffer);
|
||||
source.connect(clip.gainNode);
|
||||
|
||||
// --- CORREÇÃO: Aplica o pitch (que pode ser de stretch ou wheel) ---
|
||||
if (clip.pitch && clip.pitch !== 0) {
|
||||
source.playbackRate.value = Math.pow(2, clip.pitch / 12);
|
||||
} else {
|
||||
source.playbackRate.value = 1.0; // Garante que o modo 'trim' toque normal
|
||||
}
|
||||
// --- FIM DA CORREÇÃO ---
|
||||
// usamos Player .sync() conectando no mesmo grafo do Tone
|
||||
const toneBuf = _toToneBuffer(clip.buffer);
|
||||
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);
|
||||
|
||||
// conecta no destino principal (é um ToneAudioNode)
|
||||
try {
|
||||
gain.disconnect(); // evita duplicatas caso exista de execuções anteriores
|
||||
} catch {}
|
||||
try {
|
||||
pan.disconnect();
|
||||
} catch {}
|
||||
gain.connect(pan).connect(getMainGainNode());
|
||||
|
||||
// player sincronizado no Transport
|
||||
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;
|
||||
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 offset = clip.offsetInSeconds ?? clip.offset ?? 0;
|
||||
const dur = durationSec ?? toneBuf.duration;
|
||||
|
||||
// agenda
|
||||
player.start(occurrenceInTransportSec, offset, dur);
|
||||
|
||||
const eventId = nextEventId++;
|
||||
const clipOffset = clip.offsetInSeconds || clip.offset || 0;
|
||||
source.start(absolutePlayTime, clipOffset, durationSec);
|
||||
scheduledNodes.set(eventId, { sourceNode: source, clipId: clip.id });
|
||||
scheduledNodes.set(eventId, { player, clipId: clip.id });
|
||||
|
||||
if (callbacks.onClipScheduled) {
|
||||
callbacks.onClipScheduled(clip);
|
||||
}
|
||||
|
||||
source.onended = () => {
|
||||
// quando parar naturalmente, limpamos runtime
|
||||
player.onstop = () => {
|
||||
_handleClipEnd(eventId, clip.id);
|
||||
source.dispose();
|
||||
try { player.unsync(); } catch {}
|
||||
try { player.dispose(); } catch {}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -94,7 +126,7 @@ function _handleClipEnd(eventId, clipId) {
|
||||
|
||||
if (callbacks.onClipPlayed) {
|
||||
const clip = appState.audio.clips.find(c => c.id == clipId);
|
||||
if(clip) callbacks.onClipPlayed(clip);
|
||||
if (clip) callbacks.onClipPlayed(clip);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,26 +134,18 @@ function _schedulerTick() {
|
||||
if (!isPlaying || !audioCtx) return;
|
||||
|
||||
const now = audioCtx.currentTime;
|
||||
const logicalTime = (now - startTime) + seekTime;
|
||||
const logicalTime = (now - startTime) + (appState.audio.audioEditorSeekTime || 0);
|
||||
const scheduleWindowStartSec = logicalTime;
|
||||
const scheduleWindowEndSec = logicalTime + SCHEDULE_AHEAD_TIME_SEC;
|
||||
|
||||
for (const clip of appState.audio.clips) {
|
||||
const clipRuntime = runtimeClipState.get(clip.id) || { isScheduled: false };
|
||||
|
||||
if (clipRuntime.isScheduled) {
|
||||
continue;
|
||||
}
|
||||
if (!clip.buffer) {
|
||||
continue;
|
||||
}
|
||||
if (clipRuntime.isScheduled) continue;
|
||||
if (!clip.buffer) continue;
|
||||
|
||||
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;
|
||||
|
||||
@@ -137,11 +161,12 @@ function _schedulerTick() {
|
||||
occurrenceStartTimeSec += loopsMissed * loopDuration;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
occurrenceStartTimeSec >= scheduleWindowStartSec &&
|
||||
occurrenceStartTimeSec < scheduleWindowEndSec
|
||||
) {
|
||||
const absolutePlayTime = startTime + (occurrenceStartTimeSec - seekTime);
|
||||
const absolutePlayTime = startTime + (occurrenceStartTimeSec - (appState.audio.audioEditorSeekTime || 0));
|
||||
_scheduleClip(clip, absolutePlayTime, clipDurationSec);
|
||||
clipRuntime.isScheduled = true;
|
||||
runtimeClipState.set(clip.id, clipRuntime);
|
||||
@@ -149,23 +174,26 @@ function _schedulerTick() {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Loop de Animação (sem alterações) ---
|
||||
// --- Loop de Animação (mantido) ---
|
||||
function _animationLoop() {
|
||||
if (!isPlaying) {
|
||||
animationFrameId = null;
|
||||
return;
|
||||
}
|
||||
const now = audioCtx.currentTime;
|
||||
let newLogicalTime = (now - startTime) + seekTime;
|
||||
let newLogicalTime = (now - startTime) + (appState.audio.audioEditorSeekTime || 0);
|
||||
|
||||
if (isLoopActive) {
|
||||
if (newLogicalTime >= loopEndTimeSec) {
|
||||
const loopDuration = loopEndTimeSec - loopStartTimeSec;
|
||||
newLogicalTime = loopStartTimeSec + ((newLogicalTime - loopStartTimeSec) % loopDuration);
|
||||
startTime = now;
|
||||
seekTime = newLogicalTime;
|
||||
appState.audio.audioEditorSeekTime = newLogicalTime;
|
||||
}
|
||||
}
|
||||
logicalPlaybackTime = newLogicalTime;
|
||||
|
||||
appState.audio.audioEditorLogicalTime = newLogicalTime;
|
||||
|
||||
if (!isLoopActive) {
|
||||
let maxTime = 0;
|
||||
appState.audio.clips.forEach(clip => {
|
||||
@@ -174,15 +202,14 @@ function _animationLoop() {
|
||||
const endTime = clipStartTime + clipDuration;
|
||||
if (endTime > maxTime) maxTime = endTime;
|
||||
});
|
||||
|
||||
if (maxTime > 0 && logicalPlaybackTime >= maxTime) {
|
||||
if (maxTime > 0 && appState.audio.audioEditorLogicalTime >= maxTime) {
|
||||
stopAudioEditorPlayback(true); // Rebobina no fim
|
||||
resetPlayheadVisual();
|
||||
return;
|
||||
}
|
||||
}
|
||||
const pixelsPerSecond = getPixelsPerSecond();
|
||||
const newPositionPx = logicalPlaybackTime * pixelsPerSecond;
|
||||
const newPositionPx = appState.audio.audioEditorLogicalTime * pixelsPerSecond;
|
||||
updatePlayheadVisual(newPositionPx);
|
||||
animationFrameId = requestAnimationFrame(_animationLoop);
|
||||
}
|
||||
@@ -196,79 +223,111 @@ export function updateTransportLoop() {
|
||||
|
||||
runtimeClipState.clear();
|
||||
|
||||
scheduledNodes.forEach(nodeData => {
|
||||
// --- CORREÇÃO BUG 1: Remove a linha 'onended = null' ---
|
||||
nodeData.sourceNode.stop(0);
|
||||
nodeData.sourceNode.dispose();
|
||||
// parar e descartar players agendados
|
||||
scheduledNodes.forEach(({ player }) => {
|
||||
try { player.unsync(); } catch {}
|
||||
try { player.stop(); } catch {}
|
||||
try { player.dispose(); } catch {}
|
||||
});
|
||||
scheduledNodes.clear();
|
||||
}
|
||||
|
||||
export function startAudioEditorPlayback() {
|
||||
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') {
|
||||
audioCtx.resume();
|
||||
await audioCtx.resume();
|
||||
}
|
||||
|
||||
isPlaying = true;
|
||||
// --- CORREÇÃO BUG 2: Atualiza o estado global ---
|
||||
appState.global.isAudioEditorPlaying = true;
|
||||
|
||||
|
||||
// alinhamento de relógio próprio (mantido para o seu scheduler)
|
||||
startTime = audioCtx.currentTime;
|
||||
|
||||
// =================================================================
|
||||
// 👇 INÍCIO DA CORREÇÃO (Bugs 1 & 2)
|
||||
// =================================================================
|
||||
|
||||
updateTransportLoop();
|
||||
// 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
|
||||
|
||||
// 2. Atualize o estado global (para a agulha pular)
|
||||
// Isso garante que o estado local E o Tone estejam sincronizados.
|
||||
appState.audio.audioEditorSeekTime = timeToStart;
|
||||
|
||||
// 3. Alinhe o Tone.Transport a esse tempo
|
||||
try {
|
||||
Tone.Transport.seconds = timeToStart; // 👈 Usa o tempo sincronizado
|
||||
} catch {}
|
||||
|
||||
// =================================================================
|
||||
// 👆 FIM DA CORREÇÃO
|
||||
// =================================================================
|
||||
|
||||
updateTransportLoop();
|
||||
|
||||
console.log("%cIniciando Playback...", "color: #3498db;");
|
||||
|
||||
_schedulerTick();
|
||||
// inicia o Transport (para disparar os Players .sync())
|
||||
try {
|
||||
Tone.Transport.start();
|
||||
} catch {}
|
||||
|
||||
// mantém seu scheduler/animador
|
||||
_schedulerTick();
|
||||
schedulerIntervalId = setInterval(_schedulerTick, LOOKAHEAD_INTERVAL_MS);
|
||||
animationFrameId = requestAnimationFrame(_animationLoop);
|
||||
updateAudioEditorUI();
|
||||
const playBtn = document.getElementById("audio-editor-play-btn");
|
||||
if (playBtn) {
|
||||
playBtn.className = 'fa-solid fa-pause';
|
||||
}
|
||||
if (playBtn) playBtn.className = "fa-solid fa-pause";
|
||||
}
|
||||
|
||||
export function stopAudioEditorPlayback(rewind = false) {
|
||||
if (!isPlaying) return;
|
||||
|
||||
isPlaying = false;
|
||||
// --- CORREÇÃO BUG 2: Atualiza o estado global ---
|
||||
appState.global.isAudioEditorPlaying = false;
|
||||
|
||||
console.log(`%cParando Playback... (Rewind: ${rewind})`, "color: #d9534f;");
|
||||
|
||||
// para o Transport (para Players .sync())
|
||||
try { Tone.Transport.stop(); } catch {}
|
||||
|
||||
clearInterval(schedulerIntervalId);
|
||||
schedulerIntervalId = null;
|
||||
cancelAnimationFrame(animationFrameId);
|
||||
animationFrameId = null;
|
||||
|
||||
seekTime = logicalPlaybackTime;
|
||||
logicalPlaybackTime = 0;
|
||||
|
||||
appState.audio.audioEditorSeekTime = appState.audio.audioEditorLogicalTime || 0;
|
||||
appState.audio.audioEditorLogicalTime = 0;
|
||||
if (rewind) {
|
||||
seekTime = 0;
|
||||
appState.audio.audioEditorSeekTime = 0;
|
||||
try { Tone.Transport.seconds = 0; } catch {}
|
||||
}
|
||||
|
||||
scheduledNodes.forEach(nodeData => {
|
||||
// --- CORREÇÃO BUG 1: Remove a linha 'onended = null' ---
|
||||
nodeData.sourceNode.stop(0);
|
||||
nodeData.sourceNode.dispose();
|
||||
// parar e descartar players agendados
|
||||
scheduledNodes.forEach(({ player }) => {
|
||||
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();
|
||||
resetPlayheadVisual();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,21 +343,26 @@ export function seekAudioEditor(newTime) {
|
||||
if (wasPlaying) {
|
||||
stopAudioEditorPlayback(false); // Pausa
|
||||
}
|
||||
seekTime = newTime;
|
||||
logicalPlaybackTime = newTime;
|
||||
|
||||
appState.audio.audioEditorSeekTime = newTime;
|
||||
appState.audio.audioEditorLogicalTime = newTime;
|
||||
|
||||
try { Tone.Transport.seconds = newTime; } catch {}
|
||||
|
||||
const pixelsPerSecond = getPixelsPerSecond();
|
||||
const newPositionPx = newTime * pixelsPerSecond;
|
||||
updatePlayheadVisual(newPositionPx);
|
||||
|
||||
if (wasPlaying) {
|
||||
startAudioEditorPlayback();
|
||||
}
|
||||
}
|
||||
|
||||
export function registerCallbacks(newCallbacks) {
|
||||
if (newCallbacks.onClipScheduled) {
|
||||
callbacks.onClipScheduled = newCallbacks.onClipScheduled;
|
||||
}
|
||||
if (newCallbacks.onClipPlayed) {
|
||||
callbacks.onClipPlayed = newCallbacks.onClipPlayed;
|
||||
}
|
||||
}
|
||||
if (newCallbacks.onClipScheduled) {
|
||||
callbacks.onClipScheduled = newCallbacks.onClipScheduled;
|
||||
}
|
||||
if (newCallbacks.onClipPlayed) {
|
||||
callbacks.onClipPlayed = newCallbacks.onClipPlayed;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user