versão 2.0
This commit is contained in:
1 parent
d506332268
commit
fe735bf0a6
16 files changed
+1735
-1626
No files matched your search
@@ -0,0 +1,154 @@
|
||||
// js/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 { getPixelsPerSecond } from "../utils.js";
|
||||
|
||||
function animationLoop() {
|
||||
if (!appState.global.isAudioEditorPlaying) return;
|
||||
|
||||
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;
|
||||
});
|
||||
|
||||
if (!appState.global.isLoopActive && totalElapsedTime >= maxTime && maxTime > 0) {
|
||||
stopAudioEditorPlayback();
|
||||
resetPlayheadVisual();
|
||||
return;
|
||||
}
|
||||
|
||||
const newPositionPx = totalElapsedTime * pixelsPerSecond;
|
||||
updatePlayheadVisual(newPositionPx);
|
||||
|
||||
// ##### CORREÇÃO 1 #####
|
||||
// Salva o ID da animação para que o stop possa cancelá-lo
|
||||
appState.audio.audioEditorAnimationId = requestAnimationFrame(animationLoop);
|
||||
}
|
||||
|
||||
export function updateTransportLoop() {
|
||||
Tone.Transport.loop = appState.global.isLoopActive;
|
||||
Tone.Transport.loopStart = appState.global.loopStartTime;
|
||||
Tone.Transport.loopEnd = appState.global.loopEndTime;
|
||||
}
|
||||
|
||||
export function startAudioEditorPlayback() {
|
||||
if (appState.global.isAudioEditorPlaying) return;
|
||||
initializeAudioContext();
|
||||
Tone.Transport.cancel(); // Limpa eventos agendados anteriormente
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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();
|
||||
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;
|
||||
}
|
||||
|
||||
// (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"
|
||||
}
|
||||
}
|
||||
|
||||
appState.global.isAudioEditorPlaying = false;
|
||||
updateAudioEditorUI();
|
||||
}
|
||||
|
||||
export function seekAudioEditor(newTime) {
|
||||
const wasPlaying = appState.global.isAudioEditorPlaying;
|
||||
if (wasPlaying) {
|
||||
stopAudioEditorPlayback();
|
||||
}
|
||||
|
||||
appState.audio.audioEditorPlaybackTime = newTime;
|
||||
Tone.Transport.seconds = newTime;
|
||||
|
||||
const pixelsPerSecond = getPixelsPerSecond();
|
||||
const newPositionPx = newTime * pixelsPerSecond;
|
||||
updatePlayheadVisual(newPositionPx);
|
||||
|
||||
if (wasPlaying) {
|
||||
startAudioEditorPlayback();
|
||||
}
|
||||
}
|
||||
|
||||
export function restartAudioEditorIfPlaying() {
|
||||
if (appState.global.isAudioEditorPlaying) {
|
||||
appState.audio.audioEditorPlaybackTime = Tone.Transport.seconds;
|
||||
stopAudioEditorPlayback();
|
||||
startAudioEditorPlayback();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// js/audio_state.js
|
||||
import { DEFAULT_VOLUME, DEFAULT_PAN } from "../config.js";
|
||||
import { renderAudioEditor } from "./audio_ui.js";
|
||||
import { getMainGainNode } from "../audio.js";
|
||||
|
||||
const initialState = {
|
||||
tracks: [],
|
||||
clips: [],
|
||||
audioEditorStartTime: 0,
|
||||
audioEditorAnimationId: null,
|
||||
audioEditorPlaybackTime: 0,
|
||||
isAudioEditorLoopEnabled: false,
|
||||
};
|
||||
|
||||
export let audioState = { ...initialState };
|
||||
|
||||
export function initializeAudioState() {
|
||||
audioState.clips.forEach(clip => {
|
||||
if (clip.player) clip.player.dispose();
|
||||
if (clip.pannerNode) clip.pannerNode.dispose();
|
||||
if (clip.gainNode) clip.gainNode.dispose();
|
||||
});
|
||||
Object.assign(audioState, initialState, { tracks: [], clips: [] });
|
||||
}
|
||||
|
||||
export async function loadAudioForClip(clip) {
|
||||
if (!clip.sourcePath) return clip;
|
||||
try {
|
||||
// Cria o player e o conecta à cadeia de áudio do clipe
|
||||
clip.player = new Tone.Player();
|
||||
clip.player.chain(clip.gainNode, clip.pannerNode, getMainGainNode());
|
||||
|
||||
// Carrega o áudio e espera a conclusão
|
||||
await clip.player.load(clip.sourcePath);
|
||||
|
||||
if (clip.duration === 0) {
|
||||
clip.duration = clip.player.buffer.duration;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Falha ao carregar áudio para o clipe ${clip.name}:`, error);
|
||||
clip.player = null;
|
||||
}
|
||||
return clip;
|
||||
}
|
||||
|
||||
export function addAudioClipToTimeline(samplePath, trackId = 1, startTime = 0) {
|
||||
const newClip = {
|
||||
id: Date.now() + Math.random(),
|
||||
trackId: trackId,
|
||||
sourcePath: samplePath,
|
||||
name: samplePath.split('/').pop(),
|
||||
player: null,
|
||||
startTime: startTime,
|
||||
offset: 0,
|
||||
duration: 0,
|
||||
pitch: 0,
|
||||
volume: DEFAULT_VOLUME,
|
||||
pan: DEFAULT_PAN,
|
||||
isSoloed: true,
|
||||
// --- ADICIONADO: Nós de áudio para cada clipe ---
|
||||
gainNode: new Tone.Gain(Tone.gainToDb(DEFAULT_VOLUME)),
|
||||
pannerNode: new Tone.Panner(DEFAULT_PAN),
|
||||
};
|
||||
|
||||
audioState.clips.push(newClip);
|
||||
|
||||
loadAudioForClip(newClip).then(() => {
|
||||
renderAudioEditor();
|
||||
});
|
||||
}
|
||||
|
||||
export function updateAudioClipProperties(clipId, properties) {
|
||||
const clip = audioState.clips.find(c => c.id == clipId);
|
||||
if (clip) {
|
||||
Object.assign(clip, properties);
|
||||
}
|
||||
}
|
||||
|
||||
export function sliceAudioClip(clipId, sliceTimeInTimeline) {
|
||||
const originalClip = audioState.clips.find(c => c.id == clipId);
|
||||
if (!originalClip || sliceTimeInTimeline <= originalClip.startTime || sliceTimeInTimeline >= originalClip.startTime + originalClip.duration) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cutPointInClip = sliceTimeInTimeline - originalClip.startTime;
|
||||
|
||||
const newClip = {
|
||||
id: Date.now() + Math.random(),
|
||||
trackId: originalClip.trackId,
|
||||
sourcePath: originalClip.sourcePath,
|
||||
name: originalClip.name,
|
||||
player: originalClip.player,
|
||||
startTime: sliceTimeInTimeline,
|
||||
offset: originalClip.offset + cutPointInClip,
|
||||
duration: originalClip.duration - cutPointInClip,
|
||||
pitch: originalClip.pitch,
|
||||
volume: originalClip.volume,
|
||||
pan: originalClip.pan,
|
||||
isSoloed: false,
|
||||
gainNode: new Tone.Gain(Tone.gainToDb(originalClip.volume)),
|
||||
pannerNode: new Tone.Panner(originalClip.pan),
|
||||
};
|
||||
newClip.player.chain(newClip.gainNode, newClip.pannerNode, getMainGainNode());
|
||||
|
||||
|
||||
originalClip.duration = cutPointInClip;
|
||||
audioState.clips.push(newClip);
|
||||
}
|
||||
|
||||
export function updateClipVolume(clipId, volume) {
|
||||
const clip = audioState.clips.find((c) => c.id == 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function updateClipPan(clipId, pan) {
|
||||
const clip = audioState.clips.find((c) => c.id == clipId);
|
||||
if (clip) {
|
||||
const clampedPan = Math.max(-1, Math.min(1, pan));
|
||||
clip.pan = clampedPan;
|
||||
if (clip.pannerNode) {
|
||||
clip.pannerNode.pan.value = clampedPan;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function addAudioTrackLane() {
|
||||
const newTrackName = `Pista de Áudio ${audioState.tracks.length + 1}`;
|
||||
audioState.tracks.push({ id: Date.now(), name: newTrackName });
|
||||
// A UI será re-renderizada a partir do main.js
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
// js/audio/audio_ui.js
|
||||
import { appState } from "../state.js";
|
||||
import {
|
||||
addAudioClipToTimeline,
|
||||
updateAudioClipProperties,
|
||||
sliceAudioClip,
|
||||
} from "./audio_state.js";
|
||||
import { seekAudioEditor, restartAudioEditorIfPlaying, updateTransportLoop } from "./audio_audio.js";
|
||||
import { drawWaveform } from "../waveform.js";
|
||||
import { PIXELS_PER_BAR, ZOOM_LEVELS } from "../config.js";
|
||||
import { getPixelsPerSecond } from "../utils.js";
|
||||
|
||||
export function renderAudioEditor() {
|
||||
const audioEditor = document.querySelector('.audio-editor');
|
||||
const existingTrackContainer = document.getElementById('audio-track-container');
|
||||
if (!audioEditor || !existingTrackContainer) return;
|
||||
|
||||
// --- CRIAÇÃO E RENDERIZAÇÃO DA RÉGUA (AGORA COM WRAPPER E SPACER) ---
|
||||
let rulerWrapper = audioEditor.querySelector('.ruler-wrapper');
|
||||
if (!rulerWrapper) {
|
||||
rulerWrapper = document.createElement('div');
|
||||
rulerWrapper.className = 'ruler-wrapper';
|
||||
rulerWrapper.innerHTML = `
|
||||
<div class="ruler-spacer"></div>
|
||||
<div class="timeline-ruler"></div>
|
||||
`;
|
||||
audioEditor.insertBefore(rulerWrapper, existingTrackContainer);
|
||||
}
|
||||
|
||||
const ruler = rulerWrapper.querySelector('.timeline-ruler');
|
||||
ruler.innerHTML = ''; // Limpa a régua para redesenhar
|
||||
|
||||
const pixelsPerSecond = getPixelsPerSecond();
|
||||
|
||||
let maxTime = appState.global.loopEndTime;
|
||||
appState.audio.clips.forEach(clip => {
|
||||
const endTime = clip.startTime + clip.duration;
|
||||
if (endTime > maxTime) maxTime = endTime;
|
||||
});
|
||||
|
||||
const containerWidth = existingTrackContainer.offsetWidth;
|
||||
const contentWidth = maxTime * pixelsPerSecond;
|
||||
const totalWidth = Math.max(contentWidth, containerWidth, 2000); // Garante uma largura mínima
|
||||
|
||||
ruler.style.width = `${totalWidth}px`;
|
||||
|
||||
const zoomFactor = ZOOM_LEVELS[appState.global.zoomLevelIndex];
|
||||
const scaledBarWidth = PIXELS_PER_BAR * zoomFactor;
|
||||
|
||||
if (scaledBarWidth > 0) {
|
||||
const numberOfBars = Math.ceil(totalWidth / scaledBarWidth);
|
||||
for (let i = 1; i <= numberOfBars; i++) {
|
||||
const marker = document.createElement('div');
|
||||
marker.className = 'ruler-marker';
|
||||
marker.textContent = i;
|
||||
marker.style.left = `${(i - 1) * scaledBarWidth}px`;
|
||||
ruler.appendChild(marker);
|
||||
}
|
||||
}
|
||||
|
||||
const loopRegion = document.createElement('div');
|
||||
loopRegion.id = 'loop-region';
|
||||
loopRegion.style.left = `${appState.global.loopStartTime * pixelsPerSecond}px`;
|
||||
loopRegion.style.width = `${(appState.global.loopEndTime - appState.global.loopStartTime) * pixelsPerSecond}px`;
|
||||
loopRegion.innerHTML = `<div class="loop-handle left"></div><div class="loop-handle right"></div>`;
|
||||
loopRegion.classList.toggle("visible", appState.global.isLoopActive);
|
||||
ruler.appendChild(loopRegion);
|
||||
|
||||
// --- LISTENER DA RÉGUA PARA INTERAÇÕES (LOOP E SEEK) ---
|
||||
ruler.addEventListener('mousedown', (e) => {
|
||||
const currentPixelsPerSecond = getPixelsPerSecond();
|
||||
const loopHandle = e.target.closest('.loop-handle');
|
||||
const loopRegionBody = e.target.closest('#loop-region:not(.loop-handle)');
|
||||
|
||||
if (loopHandle) {
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
const handleType = loopHandle.classList.contains('left') ? 'left' : 'right';
|
||||
const initialMouseX = e.clientX;
|
||||
const initialStart = appState.global.loopStartTime;
|
||||
const initialEnd = appState.global.loopEndTime;
|
||||
|
||||
const onMouseMove = (moveEvent) => {
|
||||
const deltaX = moveEvent.clientX - initialMouseX;
|
||||
const deltaTime = deltaX / currentPixelsPerSecond;
|
||||
let newStart = appState.global.loopStartTime;
|
||||
let newEnd = appState.global.loopEndTime;
|
||||
|
||||
if (handleType === 'left') {
|
||||
newStart = Math.max(0, initialStart + deltaTime);
|
||||
newStart = Math.min(newStart, appState.global.loopEndTime - 0.1); // Não deixa passar do fim
|
||||
appState.global.loopStartTime = newStart;
|
||||
} else {
|
||||
newEnd = Math.max(appState.global.loopStartTime + 0.1, initialEnd + deltaTime); // Não deixa ser antes do início
|
||||
appState.global.loopEndTime = newEnd;
|
||||
}
|
||||
|
||||
updateTransportLoop();
|
||||
|
||||
// ### CORREÇÃO DE PERFORMANCE 1 ###
|
||||
// Remove a chamada para renderAudioEditor()
|
||||
// Em vez disso, atualiza o estilo do elemento 'loopRegion' diretamente
|
||||
loopRegion.style.left = `${newStart * currentPixelsPerSecond}px`;
|
||||
loopRegion.style.width = `${(newEnd - newStart) * currentPixelsPerSecond}px`;
|
||||
// ### FIM DA CORREÇÃO 1 ###
|
||||
};
|
||||
|
||||
const onMouseUp = () => {
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
// Opcional: chamar renderAudioEditor() UMA VEZ no final para garantir a sincronia
|
||||
renderAudioEditor();
|
||||
};
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
return;
|
||||
}
|
||||
|
||||
if (loopRegionBody) {
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
const initialMouseX = e.clientX;
|
||||
const initialStart = appState.global.loopStartTime;
|
||||
const initialEnd = appState.global.loopEndTime;
|
||||
const initialDuration = initialEnd - initialStart;
|
||||
|
||||
const onMouseMove = (moveEvent) => {
|
||||
const deltaX = moveEvent.clientX - initialMouseX;
|
||||
const deltaTime = deltaX / currentPixelsPerSecond;
|
||||
let newStart = Math.max(0, initialStart + deltaTime);
|
||||
let newEnd = newStart + initialDuration;
|
||||
|
||||
appState.global.loopStartTime = newStart;
|
||||
appState.global.loopEndTime = newEnd;
|
||||
|
||||
updateTransportLoop();
|
||||
|
||||
// ### CORREÇÃO DE PERFORMANCE 2 ###
|
||||
// Remove a chamada para renderAudioEditor()
|
||||
// Atualiza apenas a posição 'left' do elemento
|
||||
loopRegion.style.left = `${newStart * currentPixelsPerSecond}px`;
|
||||
// ### FIM DA CORREÇÃO 2 ###
|
||||
};
|
||||
|
||||
const onMouseUp = () => {
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
// Opcional: chamar renderAudioEditor() UMA VEZ no final
|
||||
renderAudioEditor();
|
||||
};
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
return;
|
||||
}
|
||||
|
||||
// Se o clique não foi em um handle ou no corpo do loop, faz o "seek"
|
||||
e.preventDefault();
|
||||
const handleSeek = (event) => {
|
||||
const rect = ruler.getBoundingClientRect();
|
||||
const scrollLeft = ruler.scrollLeft;
|
||||
const clickX = event.clientX - rect.left;
|
||||
const absoluteX = clickX + scrollLeft;
|
||||
const newTime = absoluteX / currentPixelsPerSecond;
|
||||
seekAudioEditor(newTime);
|
||||
};
|
||||
handleSeek(e);
|
||||
const onMouseMoveSeek = (moveEvent) => handleSeek(moveEvent);
|
||||
const onMouseUpSeek = () => { document.removeEventListener('mousemove', onMouseMoveSeek); document.removeEventListener('mouseup', onMouseUpSeek); };
|
||||
document.addEventListener('mousemove', onMouseMoveSeek);
|
||||
document.addEventListener('mouseup', onMouseUpSeek);
|
||||
});
|
||||
|
||||
// --- RECRIAÇÃO DO CONTAINER DE PISTAS PARA EVITAR LISTENERS DUPLICADOS ---
|
||||
const newTrackContainer = existingTrackContainer.cloneNode(false);
|
||||
audioEditor.replaceChild(newTrackContainer, existingTrackContainer);
|
||||
|
||||
if (appState.audio.tracks.length === 0) {
|
||||
appState.audio.tracks.push({ id: Date.now(), name: "Pista de Áudio 1" });
|
||||
}
|
||||
|
||||
// --- RENDERIZAÇÃO DAS PISTAS INDIVIDUAIS ---
|
||||
appState.audio.tracks.forEach(trackData => {
|
||||
const audioTrackLane = document.createElement('div');
|
||||
audioTrackLane.className = 'audio-track-lane';
|
||||
audioTrackLane.dataset.trackId = trackData.id;
|
||||
audioTrackLane.innerHTML = `
|
||||
<div class="track-info">
|
||||
<div class="track-info-header">
|
||||
<i class="fa-solid fa-gear"></i>
|
||||
<span class="track-name">${trackData.name}</span>
|
||||
<div class="track-mute"></div>
|
||||
</div>
|
||||
<div class="track-controls">
|
||||
<div class="knob-container">
|
||||
<div class="knob" data-control="volume"><div class="knob-indicator"></div></div>
|
||||
<span>VOL</span>
|
||||
</div>
|
||||
<div class="knob-container">
|
||||
<div class="knob" data-control="pan"><div class="knob-indicator"></div></div>
|
||||
<span>PAN</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="timeline-container">
|
||||
<div class="spectrogram-view-grid" style="width: ${totalWidth}px;"></div>
|
||||
<div class="playhead"></div>
|
||||
</div>
|
||||
`;
|
||||
newTrackContainer.appendChild(audioTrackLane);
|
||||
|
||||
const timelineContainer = audioTrackLane.querySelector('.timeline-container');
|
||||
|
||||
timelineContainer.addEventListener("dragover", (e) => { e.preventDefault(); audioTrackLane.classList.add('drag-over'); });
|
||||
timelineContainer.addEventListener("dragleave", () => audioTrackLane.classList.remove('drag-over'));
|
||||
timelineContainer.addEventListener("drop", (e) => {
|
||||
e.preventDefault();
|
||||
audioTrackLane.classList.remove('drag-over');
|
||||
const filePath = e.dataTransfer.getData("text/plain");
|
||||
if (!filePath) return;
|
||||
const rect = timelineContainer.getBoundingClientRect();
|
||||
const dropX = e.clientX - rect.left + timelineContainer.scrollLeft;
|
||||
const startTimeInSeconds = dropX / pixelsPerSecond;
|
||||
addAudioClipToTimeline(filePath, trackData.id, startTimeInSeconds);
|
||||
});
|
||||
|
||||
const grid = timelineContainer.querySelector('.spectrogram-view-grid');
|
||||
grid.style.setProperty('--bar-width', `${scaledBarWidth}px`);
|
||||
grid.style.setProperty('--four-bar-width', `${scaledBarWidth * 4}px`);
|
||||
});
|
||||
|
||||
// --- RENDERIZAÇÃO DOS CLIPS ---
|
||||
appState.audio.clips.forEach(clip => {
|
||||
const parentGrid = newTrackContainer.querySelector(`.audio-track-lane[data-track-id="${clip.trackId}"] .spectrogram-view-grid`);
|
||||
if (!parentGrid) return;
|
||||
const clipElement = document.createElement('div');
|
||||
clipElement.className = 'timeline-clip';
|
||||
clipElement.dataset.clipId = clip.id;
|
||||
clipElement.style.left = `${clip.startTime * pixelsPerSecond}px`;
|
||||
clipElement.style.width = `${clip.duration * pixelsPerSecond}px`;
|
||||
let pitchStr = clip.pitch > 0 ? `+${clip.pitch}` : `${clip.pitch}`;
|
||||
if (clip.pitch === 0) pitchStr = '';
|
||||
clipElement.innerHTML = `
|
||||
<div class="clip-resize-handle left"></div>
|
||||
<span class="clip-name">${clip.name} ${pitchStr}</span>
|
||||
<canvas class="waveform-canvas-clip"></canvas>
|
||||
<div class="clip-resize-handle right"></div>
|
||||
`;
|
||||
parentGrid.appendChild(clipElement);
|
||||
if (clip.player && clip.player.loaded) {
|
||||
const canvas = clipElement.querySelector('.waveform-canvas-clip');
|
||||
canvas.width = clip.duration * pixelsPerSecond;
|
||||
canvas.height = 40;
|
||||
const audioBuffer = clip.player.buffer.get();
|
||||
drawWaveform(canvas, audioBuffer, 'var(--accent-green)', clip.offset, clip.duration);
|
||||
}
|
||||
clipElement.addEventListener('wheel', (e) => {
|
||||
e.preventDefault();
|
||||
const clipToUpdate = appState.audio.clips.find(c => c.id == clipElement.dataset.clipId);
|
||||
if (!clipToUpdate) return;
|
||||
const direction = e.deltaY < 0 ? 1 : -1;
|
||||
let newPitch = clipToUpdate.pitch + direction;
|
||||
newPitch = Math.max(-24, Math.min(24, newPitch));
|
||||
updateAudioClipProperties(clipToUpdate.id, { pitch: newPitch });
|
||||
renderAudioEditor();
|
||||
restartAudioEditorIfPlaying();
|
||||
});
|
||||
});
|
||||
|
||||
// --- SINCRONIZAÇÃO DE SCROLL ENTRE A RÉGUA E AS PISTAS ---
|
||||
newTrackContainer.addEventListener('scroll', () => {
|
||||
const scrollPos = newTrackContainer.scrollLeft;
|
||||
if (ruler.scrollLeft !== scrollPos) {
|
||||
ruler.scrollLeft = scrollPos;
|
||||
}
|
||||
});
|
||||
|
||||
// --- EVENT LISTENER PRINCIPAL PARA INTERAÇÕES (MOVER, REDIMENSIONAR, ETC.) ---
|
||||
newTrackContainer.addEventListener('mousedown', (e) => {
|
||||
const currentPixelsPerSecond = getPixelsPerSecond();
|
||||
const handle = e.target.closest('.clip-resize-handle');
|
||||
const clipElement = e.target.closest('.timeline-clip');
|
||||
|
||||
if (appState.global.sliceToolActive && clipElement) { /* ... lógica de corte ... */ return; }
|
||||
if (handle) { /* ... lógica de redimensionamento de clipe ... */ return; }
|
||||
|
||||
if (clipElement) {
|
||||
e.preventDefault();
|
||||
const clipId = clipElement.dataset.clipId;
|
||||
const clickOffsetInClip = e.clientX - clipElement.getBoundingClientRect().left;
|
||||
clipElement.classList.add('dragging');
|
||||
let lastOverLane = clipElement.closest('.audio-track-lane');
|
||||
const onMouseMove = (moveEvent) => {
|
||||
const deltaX = moveEvent.clientX - e.clientX;
|
||||
clipElement.style.transform = `translateX(${deltaX}px)`;
|
||||
const overElement = document.elementFromPoint(moveEvent.clientX, moveEvent.clientY);
|
||||
const overLane = overElement ? overElement.closest('.audio-track-lane') : null;
|
||||
if (overLane && overLane !== lastOverLane) {
|
||||
if(lastOverLane) lastOverLane.classList.remove('drag-over');
|
||||
overLane.classList.add('drag-over');
|
||||
lastOverLane = overLane;
|
||||
}
|
||||
};
|
||||
const onMouseUp = (upEvent) => {
|
||||
clipElement.classList.remove('dragging');
|
||||
if (lastOverLane) lastOverLane.classList.remove('drag-over');
|
||||
clipElement.style.transform = '';
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
const finalLane = lastOverLane;
|
||||
if (!finalLane) return;
|
||||
const newTrackId = finalLane.dataset.trackId;
|
||||
const timelineContainer = finalLane.querySelector('.timeline-container');
|
||||
const wrapperRect = timelineContainer.getBoundingClientRect();
|
||||
const newLeftPx = (upEvent.clientX - wrapperRect.left) - clickOffsetInClip + timelineContainer.scrollLeft;
|
||||
|
||||
const constrainedLeftPx = Math.max(0, newLeftPx);
|
||||
const newStartTime = constrainedLeftPx / currentPixelsPerSecond;
|
||||
|
||||
updateAudioClipProperties(clipId, { trackId: Number(newTrackId), startTime: newStartTime });
|
||||
renderAudioEditor();
|
||||
};
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
return;
|
||||
}
|
||||
|
||||
const timelineContainer = e.target.closest('.timeline-container');
|
||||
if (timelineContainer) {
|
||||
e.preventDefault();
|
||||
const handleSeek = (event) => {
|
||||
const rect = timelineContainer.getBoundingClientRect();
|
||||
const scrollLeft = timelineContainer.scrollLeft;
|
||||
const clickX = event.clientX - rect.left;
|
||||
const absoluteX = clickX + scrollLeft;
|
||||
const newTime = absoluteX / currentPixelsPerSecond;
|
||||
seekAudioEditor(newTime);
|
||||
};
|
||||
handleSeek(e);
|
||||
const onMouseMoveSeek = (moveEvent) => handleSeek(moveEvent);
|
||||
const onMouseUpSeek = () => { document.removeEventListener('mousemove', onMouseMoveSeek); document.removeEventListener('mouseup', onMouseUpSeek); };
|
||||
document.addEventListener('mousemove', onMouseMoveSeek);
|
||||
document.addEventListener('mouseup', onMouseUpSeek);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function updateAudioEditorUI() {
|
||||
const playBtn = document.getElementById('audio-editor-play-btn');
|
||||
if (!playBtn) return;
|
||||
if (appState.global.isAudioEditorPlaying) {
|
||||
playBtn.classList.remove('fa-play');
|
||||
playBtn.classList.add('fa-pause');
|
||||
} else {
|
||||
playBtn.classList.remove('fa-pause');
|
||||
playBtn.classList.add('fa-play');
|
||||
}
|
||||
}
|
||||
|
||||
export function updatePlayheadVisual(pixels) {
|
||||
document.querySelectorAll('.audio-track-lane .playhead').forEach(ph => {
|
||||
ph.style.left = `${pixels}px`;
|
||||
});
|
||||
}
|
||||
|
||||
export function resetPlayheadVisual() {
|
||||
document.querySelectorAll('.audio-track-lane .playhead').forEach(ph => {
|
||||
ph.style.left = '0px';
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user