versão 2.0.1 - Correção do grid (Editor de Samples), loop, delete, resize, trim e streching funcionais
This commit is contained in:
1 parent
352ceecec8
commit
b3f0d13b90
9 files changed
+856
-250
No files matched your search
@@ -1,154 +1,304 @@
|
||||
// js/audio_audio.js
|
||||
// js/audio/audio_audio.js
|
||||
import { appState } from "../state.js";
|
||||
import { updateAudioEditorUI, updatePlayheadVisual, resetPlayheadVisual } from "./audio_ui.js";
|
||||
import { PIXELS_PER_STEP } from "../config.js";
|
||||
import { initializeAudioContext } from "../audio.js";
|
||||
import { initializeAudioContext, getAudioContext } from "../audio.js";
|
||||
import { getPixelsPerSecond } from "../utils.js";
|
||||
|
||||
function animationLoop() {
|
||||
if (!appState.global.isAudioEditorPlaying) return;
|
||||
// --- Configurações do Scheduler ---
|
||||
const LOOKAHEAD_INTERVAL_MS = 25.0;
|
||||
const SCHEDULE_AHEAD_TIME_SEC = 0.5; // 500ms
|
||||
|
||||
const pixelsPerSecond = getPixelsPerSecond();
|
||||
const totalElapsedTime = Tone.Transport.seconds;
|
||||
|
||||
let maxTime = 0;
|
||||
appState.audio.clips.forEach(clip => {
|
||||
const endTime = clip.startTime + clip.duration;
|
||||
if (endTime > maxTime) maxTime = endTime;
|
||||
});
|
||||
// --- Estado Interno do Engine ---
|
||||
let audioCtx = null;
|
||||
let isPlaying = false;
|
||||
let schedulerIntervalId = null;
|
||||
let animationFrameId = null;
|
||||
|
||||
if (!appState.global.isLoopActive && totalElapsedTime >= maxTime && maxTime > 0) {
|
||||
stopAudioEditorPlayback();
|
||||
resetPlayheadVisual();
|
||||
return;
|
||||
}
|
||||
|
||||
const newPositionPx = totalElapsedTime * pixelsPerSecond;
|
||||
updatePlayheadVisual(newPositionPx);
|
||||
// Sincronização de Tempo
|
||||
let startTime = 0;
|
||||
let seekTime = 0;
|
||||
let logicalPlaybackTime = 0;
|
||||
|
||||
// ##### CORREÇÃO 1 #####
|
||||
// Salva o ID da animação para que o stop possa cancelá-lo
|
||||
appState.audio.audioEditorAnimationId = requestAnimationFrame(animationLoop);
|
||||
// Configurações de Loop
|
||||
let isLoopActive = false;
|
||||
let loopStartTimeSec = 0;
|
||||
let loopEndTimeSec = 8;
|
||||
|
||||
const runtimeClipState = new Map();
|
||||
const scheduledNodes = new Map();
|
||||
let nextEventId = 0;
|
||||
|
||||
const callbacks = {
|
||||
onClipScheduled: null,
|
||||
onClipPlayed: null,
|
||||
};
|
||||
|
||||
// --- Funções Auxiliares de Tempo (sem alterações) ---
|
||||
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 _initContext() {
|
||||
if (!audioCtx) {
|
||||
initializeAudioContext();
|
||||
audioCtx = getAudioContext();
|
||||
}
|
||||
}
|
||||
|
||||
// --- Lógica Principal do Scheduler (sem alterações) ---
|
||||
|
||||
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 ---
|
||||
|
||||
const eventId = nextEventId++;
|
||||
const clipOffset = clip.offsetInSeconds || clip.offset || 0;
|
||||
source.start(absolutePlayTime, clipOffset, durationSec);
|
||||
scheduledNodes.set(eventId, { sourceNode: source, clipId: clip.id });
|
||||
|
||||
if (callbacks.onClipScheduled) {
|
||||
callbacks.onClipScheduled(clip);
|
||||
}
|
||||
|
||||
source.onended = () => {
|
||||
_handleClipEnd(eventId, clip.id);
|
||||
source.dispose();
|
||||
};
|
||||
}
|
||||
|
||||
function _handleClipEnd(eventId, clipId) {
|
||||
scheduledNodes.delete(eventId);
|
||||
runtimeClipState.delete(clipId);
|
||||
|
||||
if (callbacks.onClipPlayed) {
|
||||
const clip = appState.audio.clips.find(c => c.id == clipId);
|
||||
if(clip) callbacks.onClipPlayed(clip);
|
||||
}
|
||||
}
|
||||
|
||||
function _schedulerTick() {
|
||||
if (!isPlaying || !audioCtx) return;
|
||||
|
||||
const now = audioCtx.currentTime;
|
||||
const logicalTime = (now - startTime) + seekTime;
|
||||
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;
|
||||
}
|
||||
|
||||
const clipStartTimeSec = clip.startTimeInSeconds;
|
||||
const clipDurationSec = clip.durationInSeconds;
|
||||
|
||||
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 (occurrenceStartTimeSec < logicalTime) {
|
||||
const loopsMissed = Math.floor((logicalTime - occurrenceStartTimeSec) / loopDuration) + 1;
|
||||
occurrenceStartTimeSec += loopsMissed * loopDuration;
|
||||
}
|
||||
}
|
||||
if (
|
||||
occurrenceStartTimeSec >= scheduleWindowStartSec &&
|
||||
occurrenceStartTimeSec < scheduleWindowEndSec
|
||||
) {
|
||||
const absolutePlayTime = startTime + (occurrenceStartTimeSec - seekTime);
|
||||
_scheduleClip(clip, absolutePlayTime, clipDurationSec);
|
||||
clipRuntime.isScheduled = true;
|
||||
runtimeClipState.set(clip.id, clipRuntime);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Loop de Animação (sem alterações) ---
|
||||
function _animationLoop() {
|
||||
if (!isPlaying) {
|
||||
animationFrameId = null;
|
||||
return;
|
||||
}
|
||||
const now = audioCtx.currentTime;
|
||||
let newLogicalTime = (now - startTime) + seekTime;
|
||||
if (isLoopActive) {
|
||||
if (newLogicalTime >= loopEndTimeSec) {
|
||||
const loopDuration = loopEndTimeSec - loopStartTimeSec;
|
||||
newLogicalTime = loopStartTimeSec + ((newLogicalTime - loopStartTimeSec) % loopDuration);
|
||||
startTime = now;
|
||||
seekTime = newLogicalTime;
|
||||
}
|
||||
}
|
||||
logicalPlaybackTime = 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;
|
||||
});
|
||||
|
||||
if (maxTime > 0 && logicalPlaybackTime >= maxTime) {
|
||||
stopAudioEditorPlayback(true); // Rebobina no fim
|
||||
resetPlayheadVisual();
|
||||
return;
|
||||
}
|
||||
}
|
||||
const pixelsPerSecond = getPixelsPerSecond();
|
||||
const newPositionPx = logicalPlaybackTime * pixelsPerSecond;
|
||||
updatePlayheadVisual(newPositionPx);
|
||||
animationFrameId = requestAnimationFrame(_animationLoop);
|
||||
}
|
||||
|
||||
// --- API Pública ---
|
||||
|
||||
export function updateTransportLoop() {
|
||||
Tone.Transport.loop = appState.global.isLoopActive;
|
||||
Tone.Transport.loopStart = appState.global.loopStartTime;
|
||||
Tone.Transport.loopEnd = appState.global.loopEndTime;
|
||||
isLoopActive = appState.global.isLoopActive;
|
||||
loopStartTimeSec = appState.global.loopStartTime;
|
||||
loopEndTimeSec = appState.global.loopEndTime;
|
||||
|
||||
runtimeClipState.clear();
|
||||
|
||||
scheduledNodes.forEach(nodeData => {
|
||||
// --- CORREÇÃO BUG 1: Remove a linha 'onended = null' ---
|
||||
nodeData.sourceNode.stop(0);
|
||||
nodeData.sourceNode.dispose();
|
||||
});
|
||||
scheduledNodes.clear();
|
||||
}
|
||||
|
||||
export function startAudioEditorPlayback() {
|
||||
if (appState.global.isAudioEditorPlaying) return;
|
||||
initializeAudioContext();
|
||||
Tone.Transport.cancel(); // Limpa eventos agendados anteriormente
|
||||
if (isPlaying) return;
|
||||
|
||||
updateTransportLoop(); // Isso deve definir Tone.Transport.loop = true e Tone.Transport.loopEnd
|
||||
|
||||
// 1. Pegue a duração total do loop que a função acima definiu
|
||||
const loopInterval = Tone.Transport.loopEnd;
|
||||
|
||||
// Se loopEnd não foi definido (ex: 0 ou undefined), o loop não funcionará.
|
||||
if (!loopInterval || loopInterval === 0) {
|
||||
console.error("LoopEnd não está definido no Tone.Transport! O áudio não repetirá.");
|
||||
// Você pode querer definir um padrão aqui, mas o ideal é
|
||||
// garantir que 'updateTransportLoop' esteja definindo 'loopEnd' corretamente.
|
||||
// ex: const loopInterval = "1m"; (se for um compasso por padrão)
|
||||
_initContext();
|
||||
if (audioCtx.state === 'suspended') {
|
||||
audioCtx.resume();
|
||||
}
|
||||
|
||||
appState.audio.clips.forEach(clip => {
|
||||
if (!clip.player || !clip.player.loaded) return;
|
||||
|
||||
// 2. CORREÇÃO: Use scheduleRepeat no lugar de scheduleOnce
|
||||
Tone.Transport.scheduleRepeat((time) => {
|
||||
// Sua lógica de parâmetros está correta
|
||||
clip.gainNode.gain.value = Tone.gainToDb(clip.volume);
|
||||
clip.pannerNode.pan.value = clip.pan;
|
||||
clip.player.playbackRate = Math.pow(2, clip.pitch / 12);
|
||||
|
||||
// Inicia o player no tempo agendado
|
||||
clip.player.start(time, clip.offset, clip.duration);
|
||||
|
||||
},
|
||||
loopInterval, // <--- O intervalo de repetição (ex: "4m", "8m")
|
||||
clip.startTime // <--- Onde o clip começa dentro da linha do tempo
|
||||
);
|
||||
});
|
||||
|
||||
// 3. ADIÇÃO CRÍTICA: Inicie o transporte e atualize o estado
|
||||
Tone.Transport.start();
|
||||
isPlaying = true;
|
||||
// --- CORREÇÃO BUG 2: Atualiza o estado global ---
|
||||
appState.global.isAudioEditorPlaying = true;
|
||||
|
||||
// 4. (CORRIGIDO) Atualize a UI do botão de play
|
||||
const playBtn = document.getElementById("audio-editor-play-btn");
|
||||
if (playBtn) {
|
||||
playBtn.classList.add("active");
|
||||
// Verifica se o ícone existe antes de tentar mudá-lo
|
||||
const icon = playBtn.querySelector('i');
|
||||
if (icon) {
|
||||
icon.className = 'fa-solid fa-pause';
|
||||
}
|
||||
}
|
||||
|
||||
// ##### CORREÇÃO 2 #####
|
||||
// Inicia o loop de animação da agulha
|
||||
animationLoop();
|
||||
}
|
||||
|
||||
export function stopAudioEditorPlayback() {
|
||||
if (!appState.global.isAudioEditorPlaying) return;
|
||||
Tone.Transport.stop();
|
||||
|
||||
appState.audio.clips.forEach(clip => {
|
||||
if (clip.player && clip.player.state === 'started') {
|
||||
clip.player.stop();
|
||||
}
|
||||
});
|
||||
|
||||
appState.audio.audioEditorPlaybackTime = Tone.Transport.seconds;
|
||||
|
||||
// Esta lógica agora funcionará corretamente graças à Correção 1
|
||||
if (appState.audio.audioEditorAnimationId) {
|
||||
cancelAnimationFrame(appState.audio.audioEditorAnimationId);
|
||||
appState.audio.audioEditorAnimationId = null;
|
||||
}
|
||||
startTime = audioCtx.currentTime;
|
||||
|
||||
// (CORRIGIDO) Atualiza a UI do botão de play
|
||||
const playBtn = document.getElementById("audio-editor-play-btn");
|
||||
if (playBtn) {
|
||||
playBtn.classList.remove("active");
|
||||
// Verifica se o ícone existe antes de tentar mudá-lo
|
||||
const icon = playBtn.querySelector('i');
|
||||
if (icon) {
|
||||
icon.className = 'fa-solid fa-play'; // Muda de volta para "play"
|
||||
}
|
||||
}
|
||||
updateTransportLoop();
|
||||
|
||||
console.log("%cIniciando Playback...", "color: #3498db;");
|
||||
|
||||
appState.global.isAudioEditorPlaying = false;
|
||||
_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';
|
||||
}
|
||||
}
|
||||
|
||||
export function seekAudioEditor(newTime) {
|
||||
const wasPlaying = appState.global.isAudioEditorPlaying;
|
||||
if (wasPlaying) {
|
||||
stopAudioEditorPlayback();
|
||||
}
|
||||
|
||||
appState.audio.audioEditorPlaybackTime = newTime;
|
||||
Tone.Transport.seconds = newTime;
|
||||
export function stopAudioEditorPlayback(rewind = false) {
|
||||
if (!isPlaying) return;
|
||||
|
||||
const pixelsPerSecond = getPixelsPerSecond();
|
||||
const newPositionPx = newTime * pixelsPerSecond;
|
||||
updatePlayheadVisual(newPositionPx);
|
||||
isPlaying = false;
|
||||
// --- CORREÇÃO BUG 2: Atualiza o estado global ---
|
||||
appState.global.isAudioEditorPlaying = false;
|
||||
|
||||
console.log(`%cParando Playback... (Rewind: ${rewind})`, "color: #d9534f;");
|
||||
|
||||
if (wasPlaying) {
|
||||
startAudioEditorPlayback();
|
||||
}
|
||||
clearInterval(schedulerIntervalId);
|
||||
schedulerIntervalId = null;
|
||||
cancelAnimationFrame(animationFrameId);
|
||||
animationFrameId = null;
|
||||
|
||||
seekTime = logicalPlaybackTime;
|
||||
logicalPlaybackTime = 0;
|
||||
|
||||
if (rewind) {
|
||||
seekTime = 0;
|
||||
}
|
||||
|
||||
scheduledNodes.forEach(nodeData => {
|
||||
// --- CORREÇÃO BUG 1: Remove a linha 'onended = null' ---
|
||||
nodeData.sourceNode.stop(0);
|
||||
nodeData.sourceNode.dispose();
|
||||
});
|
||||
scheduledNodes.clear();
|
||||
runtimeClipState.clear();
|
||||
|
||||
updateAudioEditorUI();
|
||||
const playBtn = document.getElementById("audio-editor-play-btn");
|
||||
if (playBtn) {
|
||||
playBtn.className = 'fa-solid fa-play';
|
||||
}
|
||||
|
||||
if (rewind) {
|
||||
resetPlayheadVisual();
|
||||
}
|
||||
}
|
||||
|
||||
export function restartAudioEditorIfPlaying() {
|
||||
if (appState.global.isAudioEditorPlaying) {
|
||||
appState.audio.audioEditorPlaybackTime = Tone.Transport.seconds;
|
||||
stopAudioEditorPlayback();
|
||||
startAudioEditorPlayback();
|
||||
if (isPlaying) {
|
||||
stopAudioEditorPlayback(false); // Pausa
|
||||
startAudioEditorPlayback();
|
||||
}
|
||||
}
|
||||
|
||||
export function seekAudioEditor(newTime) {
|
||||
const wasPlaying = isPlaying;
|
||||
if (wasPlaying) {
|
||||
stopAudioEditorPlayback(false); // Pausa
|
||||
}
|
||||
seekTime = newTime;
|
||||
logicalPlaybackTime = newTime;
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user