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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// js/audio/audio_clipboard.js
|
||||
import { appState } from '../state.js';
|
||||
import { removeAudioClip, loadAudioForClip } from './audio_state.js';
|
||||
import { renderAudioEditor } from './audio_ui.js';
|
||||
import { getMainGainNode } from '../audio.js';
|
||||
|
||||
/**
|
||||
* Copia o clipe selecionado para a área de transferência global.
|
||||
*/
|
||||
export function copyAudioClip() {
|
||||
const clipId = appState.global.selectedClipId;
|
||||
if (!clipId) return;
|
||||
|
||||
const clip = appState.audio.clips.find(c => c.id == clipId);
|
||||
if (!clip) return;
|
||||
|
||||
// Remove a marca de "recortado" se houver
|
||||
if (appState.global.clipboard?.cutSourceId) {
|
||||
appState.global.clipboard.cutSourceId = null;
|
||||
}
|
||||
|
||||
// Cria uma cópia limpa dos dados do clipe
|
||||
const clipData = { ...clip };
|
||||
// Remove referências a nós de áudio, que devem ser únicos
|
||||
delete clipData.gainNode;
|
||||
delete clipData.pannerNode;
|
||||
delete clipData.player;
|
||||
|
||||
appState.global.clipboard = {
|
||||
type: 'audio',
|
||||
clip: clipData,
|
||||
cutSourceId: null
|
||||
};
|
||||
|
||||
console.log("Clipe copiado:", appState.global.clipboard.clip.name);
|
||||
renderAudioEditor(); // Re-renderiza para remover o visual "cut"
|
||||
}
|
||||
|
||||
/**
|
||||
* Recorta o clipe selecionado para a área de transferência global.
|
||||
*/
|
||||
export function cutAudioClip() {
|
||||
const clipId = appState.global.selectedClipId;
|
||||
if (!clipId) return;
|
||||
|
||||
// Limpa o "cut" anterior
|
||||
if (appState.global.clipboard?.cutSourceId) {
|
||||
appState.global.clipboard.cutSourceId = null;
|
||||
}
|
||||
|
||||
const clip = appState.audio.clips.find(c => c.id == clipId);
|
||||
if (!clip) return;
|
||||
|
||||
// Cria uma cópia limpa dos dados do clipe
|
||||
const clipData = { ...clip };
|
||||
delete clipData.gainNode;
|
||||
delete clipData.pannerNode;
|
||||
delete clipData.player;
|
||||
|
||||
appState.global.clipboard = {
|
||||
type: 'audio',
|
||||
clip: clipData,
|
||||
cutSourceId: clipId // Marca o ID original para exclusão
|
||||
};
|
||||
|
||||
console.log("Clipe recortado:", appState.global.clipboard.clip.name);
|
||||
renderAudioEditor(); // Re-renderiza para adicionar o visual "cut"
|
||||
}
|
||||
|
||||
/**
|
||||
* Cola o clipe da área de transferência na timeline.
|
||||
* @param {number} targetTrackId - O ID da pista onde colar.
|
||||
* @param {number} targetTimeInSeconds - O tempo (em segundos) onde colar.
|
||||
*/
|
||||
export function pasteAudioClip(targetTrackId, targetTimeInSeconds) {
|
||||
const clipboard = appState.global.clipboard;
|
||||
if (!clipboard || clipboard.type !== 'audio' || !clipboard.clip) {
|
||||
console.warn("Área de transferência vazia ou inválida para colar áudio.");
|
||||
return;
|
||||
}
|
||||
|
||||
const clipToPaste = clipboard.clip;
|
||||
|
||||
// Se for um "recorte", primeiro remove o clipe original
|
||||
if (clipboard.cutSourceId) {
|
||||
removeAudioClip(clipboard.cutSourceId); //
|
||||
clipboard.cutSourceId = null; // Limpa para que não remova de novo
|
||||
}
|
||||
|
||||
// Cria um novo clipe a partir dos dados copiados
|
||||
const newClip = {
|
||||
...clipToPaste,
|
||||
id: Date.now() + Math.random(), // ID novo e único
|
||||
trackId: targetTrackId,
|
||||
startTimeInSeconds: targetTimeInSeconds,
|
||||
|
||||
// Cria novos nós de áudio
|
||||
gainNode: new Tone.Gain(Tone.gainToDb(clipToPaste.volume || 1.0)),
|
||||
pannerNode: new Tone.Panner(clipToPaste.pan || 0),
|
||||
|
||||
player: null,
|
||||
// O buffer será copiado/referenciado
|
||||
};
|
||||
|
||||
newClip.gainNode.connect(newClip.pannerNode);
|
||||
newClip.pannerNode.connect(getMainGainNode()); //
|
||||
|
||||
appState.audio.clips.push(newClip);
|
||||
|
||||
// Como o buffer já deve existir no clipe original,
|
||||
// não precisamos de 'loadAudioForClip', mas chamamos
|
||||
// para garantir (caso a fonte seja um 'sourcePath').
|
||||
// A função 'loadAudioForClip' precisa ser inteligente
|
||||
// para não recarregar se o buffer já existir.
|
||||
loadAudioForClip(newClip).then(() => { //
|
||||
renderAudioEditor();
|
||||
});
|
||||
}
|
||||
@@ -1,18 +1,89 @@
|
||||
// js/audio_state.js
|
||||
// js/audio/audio_state.js
|
||||
import { DEFAULT_VOLUME, DEFAULT_PAN } from "../config.js";
|
||||
import { renderAudioEditor } from "./audio_ui.js";
|
||||
import { getMainGainNode } from "../audio.js";
|
||||
import { getAudioContext } from "../audio.js";
|
||||
import { getMainGainNode, getAudioContext } from "../audio.js";
|
||||
import * as Tone from "https://esm.sh/tone";
|
||||
|
||||
export let audioState = {
|
||||
tracks: [],
|
||||
clips: [],
|
||||
// --- TEMPOS MOVIDOS DO audio_audio.js PARA O ESTADO GLOBAL ---
|
||||
audioEditorSeekTime: 0,
|
||||
audioEditorLogicalTime: 0,
|
||||
// --- FIM DA MUDANÇA ---
|
||||
audioEditorStartTime: 0,
|
||||
audioEditorAnimationId: null,
|
||||
audioEditorPlaybackTime: 0,
|
||||
isAudioEditorLoopEnabled: false,
|
||||
};
|
||||
|
||||
// ==== SNAPSHOT: exportação do estado atual (tracks + clips) ====
|
||||
export function getAudioSnapshot() {
|
||||
// Se seu estado “oficial” é audioState.* use ele;
|
||||
// se for appState.audio.* troque abaixo.
|
||||
const tracks = (audioState.tracks || []).map(t => ({
|
||||
id: t.id, name: t.name
|
||||
}));
|
||||
|
||||
const clips = (audioState.clips || []).map(c => ({
|
||||
id: c.id,
|
||||
trackId: c.trackId,
|
||||
name: c.name,
|
||||
sourcePath: c.sourcePath || null, // URL do asset (precisa ser acessível)
|
||||
startTimeInSeconds: c.startTimeInSeconds || 0,
|
||||
durationInSeconds: c.durationInSeconds || (c.buffer?.duration || 0),
|
||||
offset: c.offset || 0,
|
||||
pitch: c.pitch || 0,
|
||||
volume: c.volume ?? 1,
|
||||
pan: c.pan ?? 0,
|
||||
originalDuration: c.originalDuration || (c.buffer?.duration || 0),
|
||||
}));
|
||||
|
||||
return { tracks, clips };
|
||||
}
|
||||
|
||||
// ==== SNAPSHOT: aplicação do estado recebido ====
|
||||
export async function applyAudioSnapshot(snapshot) {
|
||||
if (!snapshot) return;
|
||||
|
||||
// aplica trilhas (mantém ids/nome)
|
||||
if (Array.isArray(snapshot.tracks) && snapshot.tracks.length) {
|
||||
audioState.tracks = snapshot.tracks.map(t => ({ id: t.id, name: t.name }));
|
||||
}
|
||||
|
||||
// insere clipes usando os MESMOS ids do emissor (idempotente)
|
||||
if (Array.isArray(snapshot.clips)) {
|
||||
for (const c of snapshot.clips) {
|
||||
// evita duplicar se já existir (idempotência)
|
||||
if (audioState.clips.some(x => String(x.id) === String(c.id))) continue;
|
||||
|
||||
// usa a própria função de criação (agora ela aceita id e nome)
|
||||
// assinatura: addAudioClipToTimeline(samplePath, trackId, start, clipId, name)
|
||||
addAudioClipToTimeline(c.sourcePath, c.trackId, c.startTimeInSeconds, c.id, c.name);
|
||||
|
||||
// aplica propriedades adicionais (dur/offset/pitch/vol/pan) no mesmo id
|
||||
const idx = audioState.clips.findIndex(x => String(x.id) === String(c.id));
|
||||
if (idx >= 0) {
|
||||
const clip = audioState.clips[idx];
|
||||
clip.durationInSeconds = c.durationInSeconds;
|
||||
clip.offset = c.offset;
|
||||
clip.pitch = c.pitch;
|
||||
clip.volume = c.volume;
|
||||
clip.pan = c.pan;
|
||||
clip.originalDuration = c.originalDuration;
|
||||
|
||||
// reflete nos nós Tone já criados
|
||||
if (clip.gainNode) clip.gainNode.gain.value = clip.volume ?? 1;
|
||||
if (clip.pannerNode) clip.pannerNode.pan.value = clip.pan ?? 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// re-render geral do editor
|
||||
renderAudioEditor();
|
||||
}
|
||||
|
||||
|
||||
export function initializeAudioState() {
|
||||
audioState.clips.forEach(clip => {
|
||||
if (clip.pannerNode) clip.pannerNode.dispose();
|
||||
@@ -21,6 +92,10 @@ export function initializeAudioState() {
|
||||
Object.assign(audioState, {
|
||||
tracks: [],
|
||||
clips: [],
|
||||
// --- ADICIONADO ---
|
||||
audioEditorSeekTime: 0,
|
||||
audioEditorLogicalTime: 0,
|
||||
// --- FIM ---
|
||||
audioEditorStartTime: 0,
|
||||
audioEditorAnimationId: null,
|
||||
audioEditorPlaybackTime: 0,
|
||||
@@ -29,6 +104,16 @@ export function initializeAudioState() {
|
||||
}
|
||||
|
||||
export async function loadAudioForClip(clip) {
|
||||
// --- ADIÇÃO ---
|
||||
// Se já temos um buffer (do bounce ou colagem), não faz fetch
|
||||
if (clip.buffer) {
|
||||
// Garante que as durações estão corretas
|
||||
if (clip.originalDuration === 0) clip.originalDuration = clip.buffer.duration;
|
||||
if (clip.durationInSeconds === 0) clip.durationInSeconds = clip.buffer.duration;
|
||||
return clip;
|
||||
}
|
||||
// --- FIM DA ADIÇÃO ---
|
||||
|
||||
if (!clip.sourcePath) return clip;
|
||||
|
||||
const audioCtx = getAudioContext();
|
||||
@@ -58,51 +143,82 @@ export async function loadAudioForClip(clip) {
|
||||
return clip;
|
||||
}
|
||||
|
||||
export function addAudioClipToTimeline(samplePath, trackId = 1, startTime = 0, clipName = null) {
|
||||
// helper de id (fallback se o emissor não mandar)
|
||||
function genClipId() {
|
||||
return (crypto?.randomUUID?.() || `clip_${Date.now()}_${Math.floor(Math.random()*1e6)}`);
|
||||
}
|
||||
|
||||
// --- FUNÇÃO MODIFICADA ---
|
||||
// agora aceita clipId e clipName vindos do emissor; mantém compat com chamadas antigas
|
||||
export function addAudioClipToTimeline(samplePath, trackId = 1, startTime = 0, clipIdOrName = null, nameOrBuffer = null, maybeBuffer = null) {
|
||||
// compat: se passaram (filePath, trackId, start, clipId)
|
||||
// mas versões antigas chamavam (filePath, trackId, start) ou (filePath, trackId, start, name, buffer)
|
||||
let incomingId = null;
|
||||
let clipName = null;
|
||||
let existingBuffer = null;
|
||||
|
||||
// heurística: se clipIdOrName parece um UUID/clip_ → é id, senão é nome
|
||||
if (typeof clipIdOrName === 'string' && (clipIdOrName.startsWith('clip_') || clipIdOrName.length >= 16)) {
|
||||
incomingId = clipIdOrName;
|
||||
clipName = (typeof nameOrBuffer === 'string') ? nameOrBuffer : null;
|
||||
existingBuffer = maybeBuffer || (nameOrBuffer && typeof nameOrBuffer !== 'string' ? nameOrBuffer : null);
|
||||
} else {
|
||||
// assinatura antiga: 4º arg era nome
|
||||
clipName = (typeof clipIdOrName === 'string') ? clipIdOrName : null;
|
||||
existingBuffer = (nameOrBuffer && typeof nameOrBuffer !== 'string') ? nameOrBuffer : null;
|
||||
}
|
||||
|
||||
const finalId = incomingId || genClipId();
|
||||
|
||||
// idempotência: se o id já existe, não duplica
|
||||
if (audioState.clips.some(c => String(c.id) === String(finalId))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const newClip = {
|
||||
id: Date.now() + Math.random(),
|
||||
id: finalId,
|
||||
trackId: trackId,
|
||||
sourcePath: samplePath,
|
||||
|
||||
// --- MODIFICAÇÃO AQUI ---
|
||||
// Usa o nome fornecido, ou extrai do caminho se não for fornecido
|
||||
name: clipName || samplePath.split('/').pop(),
|
||||
sourcePath: samplePath, // Pode ser null se existingBuffer for fornecido
|
||||
name: clipName || (samplePath ? String(samplePath).split('/').pop() : 'Bounced Clip'),
|
||||
|
||||
startTimeInSeconds: startTime,
|
||||
offset: 0,
|
||||
durationInSeconds: 0,
|
||||
originalDuration: 0, // Será preenchido pelo loadAudioForClip
|
||||
originalDuration: 0,
|
||||
|
||||
pitch: 0,
|
||||
volume: DEFAULT_VOLUME,
|
||||
pan: DEFAULT_PAN,
|
||||
|
||||
gainNode: new Tone.Gain(Tone.gainToDb(DEFAULT_VOLUME)),
|
||||
pannerNode: new Tone.Panner(DEFAULT_PAN),
|
||||
|
||||
buffer: null,
|
||||
buffer: existingBuffer || null,
|
||||
player: null,
|
||||
};
|
||||
|
||||
// volume linear (0–1)
|
||||
newClip.gainNode = new Tone.Gain(DEFAULT_VOLUME);
|
||||
newClip.pannerNode = new Tone.Panner(DEFAULT_PAN);
|
||||
|
||||
// conecta tudo no grafo do Tone (mesmo contexto)
|
||||
newClip.gainNode.connect(newClip.pannerNode);
|
||||
newClip.pannerNode.connect(getMainGainNode());
|
||||
|
||||
audioState.clips.push(newClip);
|
||||
|
||||
// loadAudioForClip agora vai lidar com 'existingBuffer'
|
||||
loadAudioForClip(newClip).then(() => {
|
||||
renderAudioEditor();
|
||||
});
|
||||
}
|
||||
|
||||
export function updateAudioClipProperties(clipId, properties) {
|
||||
const clip = audioState.clips.find(c => c.id == clipId);
|
||||
const clip = audioState.clips.find(c => String(c.id) == String(clipId));
|
||||
if (clip) {
|
||||
Object.assign(clip, properties);
|
||||
}
|
||||
}
|
||||
|
||||
export function sliceAudioClip(clipId, sliceTimeInTimeline) {
|
||||
const originalClip = audioState.clips.find(c => c.id == clipId);
|
||||
const originalClip = audioState.clips.find(c => String(c.id) == String(clipId));
|
||||
|
||||
if (!originalClip ||
|
||||
sliceTimeInTimeline <= originalClip.startTimeInSeconds ||
|
||||
@@ -115,7 +231,7 @@ export function sliceAudioClip(clipId, sliceTimeInTimeline) {
|
||||
const cutPointInClip = sliceTimeInTimeline - originalClip.startTimeInSeconds;
|
||||
|
||||
const newClip = {
|
||||
id: Date.now() + Math.random(),
|
||||
id: genClipId(),
|
||||
trackId: originalClip.trackId,
|
||||
sourcePath: originalClip.sourcePath,
|
||||
name: originalClip.name,
|
||||
@@ -132,7 +248,7 @@ export function sliceAudioClip(clipId, sliceTimeInTimeline) {
|
||||
volume: originalClip.volume,
|
||||
pan: originalClip.pan,
|
||||
|
||||
gainNode: new Tone.Gain(Tone.gainToDb(originalClip.volume)),
|
||||
gainNode: new Tone.Gain(originalClip.volume),
|
||||
pannerNode: new Tone.Panner(originalClip.pan),
|
||||
|
||||
player: null
|
||||
@@ -148,20 +264,19 @@ export function sliceAudioClip(clipId, sliceTimeInTimeline) {
|
||||
console.log("Clipe dividido. Original:", originalClip, "Novo:", newClip);
|
||||
}
|
||||
|
||||
// ... (resto do arquivo 'audio_state.js' sem alterações) ...
|
||||
export function updateClipVolume(clipId, volume) {
|
||||
const clip = audioState.clips.find((c) => c.id == clipId);
|
||||
const clip = audioState.clips.find((c) => String(c.id) == String(clipId));
|
||||
if (clip) {
|
||||
const clampedVolume = Math.max(0, Math.min(1.5, volume));
|
||||
clip.volume = clampedVolume;
|
||||
if (clip.gainNode) {
|
||||
clip.gainNode.gain.value = Tone.gainToDb(clampedVolume);
|
||||
clip.gainNode.gain.value = clampedVolume;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function updateClipPan(clipId, pan) {
|
||||
const clip = audioState.clips.find((c) => c.id == clipId);
|
||||
const clip = audioState.clips.find((c) => String(c.id) == String(clipId));
|
||||
if (clip) {
|
||||
const clampedPan = Math.max(-1, Math.min(1, pan));
|
||||
clip.pan = clampedPan;
|
||||
@@ -177,19 +292,19 @@ export function addAudioTrackLane() {
|
||||
}
|
||||
|
||||
export function removeAudioClip(clipId) {
|
||||
const clipIndex = audioState.clips.findIndex(c => c.id == clipId);
|
||||
const clipIndex = audioState.clips.findIndex(c => String(c.id) == String(clipId));
|
||||
if (clipIndex === -1) return false; // Retorna false se não encontrou
|
||||
|
||||
const clip = audioState.clips[clipIndex];
|
||||
|
||||
// 1. Limpa os nós de áudio do Tone.js
|
||||
if (clip.gainNode) {
|
||||
clip.gainNode.disconnect();
|
||||
clip.gainNode.dispose();
|
||||
try { clip.gainNode.disconnect(); } catch {}
|
||||
try { clip.gainNode.dispose(); } catch {}
|
||||
}
|
||||
if (clip.pannerNode) {
|
||||
clip.pannerNode.disconnect();
|
||||
clip.pannerNode.dispose();
|
||||
try { clip.pannerNode.disconnect(); } catch {}
|
||||
try { clip.pannerNode.dispose(); } catch {}
|
||||
}
|
||||
|
||||
// 2. Remove o clipe do array de estado
|
||||
@@ -197,4 +312,4 @@ export function removeAudioClip(clipId) {
|
||||
|
||||
// 3. Retorna true para o chamador (Controller)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user