feat: implement Phase 7.1-7.2 multi-track infrastructure
Added core multi-track support with track management and controls: **Track Types & Utilities:** - Track interface with audio buffer, controls (volume/pan/solo/mute) - Track utility functions for creation, mixing, and gain calculation - Track color system with 9 preset colors - Configurable track heights (60-300px) **Components:** - TrackHeader: Collapsible track controls with inline name editing - Solo/Mute buttons with visual feedback - Volume slider (0-100%) and Pan control (L-C-R) - Track color indicator and remove button - Track: Waveform display component with canvas rendering - Click-to-seek on waveform - Playhead visualization - Support for collapsed state - TrackList: Container managing multiple tracks - Scrollable track list with custom scrollbar - Add track button - Empty state UI **State Management:** - useMultiTrack hook with localStorage persistence - Add/remove/update/reorder track operations - Track buffer management Features implemented: - ✅ Track creation and removal - ✅ Track naming (editable) - ✅ Track colors - ✅ Solo/Mute per track - ✅ Volume fader per track (0-100%) - ✅ Pan control per track (L-C-R) - ✅ Track collapse/expand - ✅ Track height configuration - ✅ Waveform visualization per track - ✅ Multi-track audio mixing utilities Next: Integrate into AudioEditor and implement multi-track playback 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
172
components/tracks/Track.tsx
Normal file
172
components/tracks/Track.tsx
Normal file
@@ -0,0 +1,172 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import type { Track as TrackType } from '@/types/track';
|
||||
import { TrackHeader } from './TrackHeader';
|
||||
import { cn } from '@/lib/utils/cn';
|
||||
|
||||
export interface TrackProps {
|
||||
track: TrackType;
|
||||
zoom: number;
|
||||
currentTime: number;
|
||||
duration: number;
|
||||
onToggleMute: () => void;
|
||||
onToggleSolo: () => void;
|
||||
onToggleCollapse: () => void;
|
||||
onVolumeChange: (volume: number) => void;
|
||||
onPanChange: (pan: number) => void;
|
||||
onRemove: () => void;
|
||||
onNameChange: (name: string) => void;
|
||||
onSeek?: (time: number) => void;
|
||||
}
|
||||
|
||||
export function Track({
|
||||
track,
|
||||
zoom,
|
||||
currentTime,
|
||||
duration,
|
||||
onToggleMute,
|
||||
onToggleSolo,
|
||||
onToggleCollapse,
|
||||
onVolumeChange,
|
||||
onPanChange,
|
||||
onRemove,
|
||||
onNameChange,
|
||||
onSeek,
|
||||
}: TrackProps) {
|
||||
const canvasRef = React.useRef<HTMLCanvasElement>(null);
|
||||
const containerRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
// Draw waveform
|
||||
React.useEffect(() => {
|
||||
if (!track.audioBuffer || !canvasRef.current || track.collapsed) return;
|
||||
|
||||
const canvas = canvasRef.current;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
|
||||
canvas.width = rect.width * dpr;
|
||||
canvas.height = rect.height * dpr;
|
||||
ctx.scale(dpr, dpr);
|
||||
|
||||
const width = rect.width;
|
||||
const height = rect.height;
|
||||
|
||||
// Clear canvas
|
||||
ctx.fillStyle = 'rgb(15, 23, 42)';
|
||||
ctx.fillRect(0, 0, width, height);
|
||||
|
||||
const buffer = track.audioBuffer;
|
||||
const channelData = buffer.getChannelData(0);
|
||||
const samplesPerPixel = Math.floor(buffer.length / (width * zoom));
|
||||
|
||||
// Draw waveform
|
||||
ctx.fillStyle = track.color;
|
||||
ctx.strokeStyle = track.color;
|
||||
ctx.lineWidth = 1;
|
||||
|
||||
for (let x = 0; x < width; x++) {
|
||||
const startSample = Math.floor(x * samplesPerPixel);
|
||||
const endSample = Math.floor((x + 1) * samplesPerPixel);
|
||||
|
||||
let min = 1.0;
|
||||
let max = -1.0;
|
||||
|
||||
for (let i = startSample; i < endSample && i < channelData.length; i++) {
|
||||
const sample = channelData[i];
|
||||
if (sample < min) min = sample;
|
||||
if (sample > max) max = sample;
|
||||
}
|
||||
|
||||
const y1 = (height / 2) * (1 - max);
|
||||
const y2 = (height / 2) * (1 - min);
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, y1);
|
||||
ctx.lineTo(x, y2);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// Draw center line
|
||||
ctx.strokeStyle = 'rgba(148, 163, 184, 0.2)';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(0, height / 2);
|
||||
ctx.lineTo(width, height / 2);
|
||||
ctx.stroke();
|
||||
|
||||
// Draw playhead
|
||||
if (duration > 0) {
|
||||
const playheadX = (currentTime / duration) * width;
|
||||
ctx.strokeStyle = 'rgba(59, 130, 246, 0.8)';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(playheadX, 0);
|
||||
ctx.lineTo(playheadX, height);
|
||||
ctx.stroke();
|
||||
}
|
||||
}, [track.audioBuffer, track.color, track.collapsed, zoom, currentTime, duration]);
|
||||
|
||||
const handleCanvasClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
|
||||
if (!onSeek || !duration) return;
|
||||
|
||||
const rect = e.currentTarget.getBoundingClientRect();
|
||||
const x = e.clientX - rect.left;
|
||||
const clickTime = (x / rect.width) * duration;
|
||||
onSeek(clickTime);
|
||||
};
|
||||
|
||||
if (track.collapsed) {
|
||||
return (
|
||||
<div className="border-b border-border">
|
||||
<TrackHeader
|
||||
track={track}
|
||||
onToggleMute={onToggleMute}
|
||||
onToggleSolo={onToggleSolo}
|
||||
onToggleCollapse={onToggleCollapse}
|
||||
onVolumeChange={onVolumeChange}
|
||||
onPanChange={onPanChange}
|
||||
onRemove={onRemove}
|
||||
onNameChange={onNameChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn(
|
||||
'border-b border-border',
|
||||
track.selected && 'ring-2 ring-primary ring-inset'
|
||||
)}
|
||||
>
|
||||
<TrackHeader
|
||||
track={track}
|
||||
onToggleMute={onToggleMute}
|
||||
onToggleSolo={onToggleSolo}
|
||||
onToggleCollapse={onToggleCollapse}
|
||||
onVolumeChange={onVolumeChange}
|
||||
onPanChange={onPanChange}
|
||||
onRemove={onRemove}
|
||||
onNameChange={onNameChange}
|
||||
/>
|
||||
<div className="relative" style={{ height: track.height }}>
|
||||
{track.audioBuffer ? (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
className="w-full h-full cursor-pointer"
|
||||
onClick={handleCanvasClick}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full text-sm text-muted-foreground">
|
||||
No audio loaded
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
180
components/tracks/TrackHeader.tsx
Normal file
180
components/tracks/TrackHeader.tsx
Normal file
@@ -0,0 +1,180 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { Volume2, VolumeX, Headphones, Mic, X, ChevronDown, ChevronRight } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Slider } from '@/components/ui/Slider';
|
||||
import type { Track } from '@/types/track';
|
||||
import { cn } from '@/lib/utils/cn';
|
||||
|
||||
export interface TrackHeaderProps {
|
||||
track: Track;
|
||||
onToggleMute: () => void;
|
||||
onToggleSolo: () => void;
|
||||
onToggleCollapse: () => void;
|
||||
onVolumeChange: (volume: number) => void;
|
||||
onPanChange: (pan: number) => void;
|
||||
onRemove: () => void;
|
||||
onNameChange: (name: string) => void;
|
||||
}
|
||||
|
||||
export function TrackHeader({
|
||||
track,
|
||||
onToggleMute,
|
||||
onToggleSolo,
|
||||
onToggleCollapse,
|
||||
onVolumeChange,
|
||||
onPanChange,
|
||||
onRemove,
|
||||
onNameChange,
|
||||
}: TrackHeaderProps) {
|
||||
const [isEditingName, setIsEditingName] = React.useState(false);
|
||||
const [nameInput, setNameInput] = React.useState(track.name);
|
||||
const inputRef = React.useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleNameClick = () => {
|
||||
setIsEditingName(true);
|
||||
setNameInput(track.name);
|
||||
};
|
||||
|
||||
const handleNameBlur = () => {
|
||||
setIsEditingName(false);
|
||||
if (nameInput.trim()) {
|
||||
onNameChange(nameInput.trim());
|
||||
} else {
|
||||
setNameInput(track.name);
|
||||
}
|
||||
};
|
||||
|
||||
const handleNameKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
inputRef.current?.blur();
|
||||
} else if (e.key === 'Escape') {
|
||||
setNameInput(track.name);
|
||||
setIsEditingName(false);
|
||||
}
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
if (isEditingName && inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
inputRef.current.select();
|
||||
}
|
||||
}, [isEditingName]);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 px-3 py-2 border-b border-border bg-card">
|
||||
{/* Collapse Toggle */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onToggleCollapse}
|
||||
title={track.collapsed ? 'Expand track' : 'Collapse track'}
|
||||
>
|
||||
{track.collapsed ? (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Track Color Indicator */}
|
||||
<div
|
||||
className="w-1 h-8 rounded-full"
|
||||
style={{ backgroundColor: track.color }}
|
||||
/>
|
||||
|
||||
{/* Track Name */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{isEditingName ? (
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={nameInput}
|
||||
onChange={(e) => setNameInput(e.target.value)}
|
||||
onBlur={handleNameBlur}
|
||||
onKeyDown={handleNameKeyDown}
|
||||
className="w-full px-2 py-1 text-sm font-medium bg-background border border-border rounded"
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
onClick={handleNameClick}
|
||||
className="px-2 py-1 text-sm font-medium text-foreground truncate cursor-pointer hover:bg-accent rounded"
|
||||
title={track.name}
|
||||
>
|
||||
{track.name}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Solo Button */}
|
||||
<Button
|
||||
variant={track.solo ? 'secondary' : 'ghost'}
|
||||
size="icon-sm"
|
||||
onClick={onToggleSolo}
|
||||
title="Solo track"
|
||||
className={cn(track.solo && 'bg-yellow-500/20 hover:bg-yellow-500/30')}
|
||||
>
|
||||
<Headphones className={cn('h-4 w-4', track.solo && 'text-yellow-500')} />
|
||||
</Button>
|
||||
|
||||
{/* Mute Button */}
|
||||
<Button
|
||||
variant={track.mute ? 'secondary' : 'ghost'}
|
||||
size="icon-sm"
|
||||
onClick={onToggleMute}
|
||||
title="Mute track"
|
||||
className={cn(track.mute && 'bg-red-500/20 hover:bg-red-500/30')}
|
||||
>
|
||||
{track.mute ? (
|
||||
<VolumeX className="h-4 w-4 text-red-500" />
|
||||
) : (
|
||||
<Volume2 className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Volume Slider */}
|
||||
<div className="flex items-center gap-2 w-24">
|
||||
<Slider
|
||||
value={[track.volume]}
|
||||
onValueChange={([value]) => onVolumeChange(value)}
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.01}
|
||||
className="flex-1"
|
||||
title={`Volume: ${Math.round(track.volume * 100)}%`}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground w-8 text-right">
|
||||
{Math.round(track.volume * 100)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Pan Knob (simplified as slider) */}
|
||||
<div className="flex items-center gap-2 w-20">
|
||||
<Slider
|
||||
value={[track.pan]}
|
||||
onValueChange={([value]) => onPanChange(value)}
|
||||
min={-1}
|
||||
max={1}
|
||||
step={0.01}
|
||||
className="flex-1"
|
||||
title={`Pan: ${track.pan === 0 ? 'C' : track.pan < 0 ? `L${Math.abs(Math.round(track.pan * 100))}` : `R${Math.round(track.pan * 100)}`}`}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground w-6 text-right">
|
||||
{track.pan === 0 ? 'C' : track.pan < 0 ? `L` : 'R'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Remove Button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onRemove}
|
||||
title="Remove track"
|
||||
className="text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
86
components/tracks/TrackList.tsx
Normal file
86
components/tracks/TrackList.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Track } from './Track';
|
||||
import type { Track as TrackType } from '@/types/track';
|
||||
|
||||
export interface TrackListProps {
|
||||
tracks: TrackType[];
|
||||
zoom: number;
|
||||
currentTime: number;
|
||||
duration: number;
|
||||
onAddTrack: () => void;
|
||||
onRemoveTrack: (trackId: string) => void;
|
||||
onUpdateTrack: (trackId: string, updates: Partial<TrackType>) => void;
|
||||
onSeek?: (time: number) => void;
|
||||
}
|
||||
|
||||
export function TrackList({
|
||||
tracks,
|
||||
zoom,
|
||||
currentTime,
|
||||
duration,
|
||||
onAddTrack,
|
||||
onRemoveTrack,
|
||||
onUpdateTrack,
|
||||
onSeek,
|
||||
}: TrackListProps) {
|
||||
if (tracks.length === 0) {
|
||||
return (
|
||||
<div className="flex-1 flex flex-col items-center justify-center gap-4 text-muted-foreground">
|
||||
<p className="text-sm">No tracks yet. Add a track to get started.</p>
|
||||
<Button onClick={onAddTrack} variant="secondary">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Track
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col overflow-hidden">
|
||||
{/* Track List */}
|
||||
<div className="flex-1 overflow-y-auto custom-scrollbar">
|
||||
{tracks.map((track) => (
|
||||
<Track
|
||||
key={track.id}
|
||||
track={track}
|
||||
zoom={zoom}
|
||||
currentTime={currentTime}
|
||||
duration={duration}
|
||||
onToggleMute={() =>
|
||||
onUpdateTrack(track.id, { mute: !track.mute })
|
||||
}
|
||||
onToggleSolo={() =>
|
||||
onUpdateTrack(track.id, { solo: !track.solo })
|
||||
}
|
||||
onToggleCollapse={() =>
|
||||
onUpdateTrack(track.id, { collapsed: !track.collapsed })
|
||||
}
|
||||
onVolumeChange={(volume) =>
|
||||
onUpdateTrack(track.id, { volume })
|
||||
}
|
||||
onPanChange={(pan) =>
|
||||
onUpdateTrack(track.id, { pan })
|
||||
}
|
||||
onRemove={() => onRemoveTrack(track.id)}
|
||||
onNameChange={(name) =>
|
||||
onUpdateTrack(track.id, { name })
|
||||
}
|
||||
onSeek={onSeek}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Add Track Button */}
|
||||
<div className="p-2 border-t border-border bg-card">
|
||||
<Button onClick={onAddTrack} variant="outline" size="sm" className="w-full">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Track
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
132
lib/audio/track-utils.ts
Normal file
132
lib/audio/track-utils.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* Track utility functions
|
||||
*/
|
||||
|
||||
import type { Track, TrackColor } from '@/types/track';
|
||||
import { DEFAULT_TRACK_HEIGHT, TRACK_COLORS } from '@/types/track';
|
||||
|
||||
/**
|
||||
* Generate a unique track ID
|
||||
*/
|
||||
export function generateTrackId(): string {
|
||||
return `track-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new empty track
|
||||
*/
|
||||
export function createTrack(name?: string, color?: TrackColor): Track {
|
||||
const colors: TrackColor[] = ['blue', 'green', 'purple', 'orange', 'pink', 'indigo', 'yellow', 'red'];
|
||||
const randomColor = colors[Math.floor(Math.random() * colors.length)];
|
||||
|
||||
return {
|
||||
id: generateTrackId(),
|
||||
name: name || 'New Track',
|
||||
color: TRACK_COLORS[color || randomColor],
|
||||
height: DEFAULT_TRACK_HEIGHT,
|
||||
audioBuffer: null,
|
||||
volume: 0.8,
|
||||
pan: 0,
|
||||
mute: false,
|
||||
solo: false,
|
||||
recordEnabled: false,
|
||||
collapsed: false,
|
||||
selected: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a track from an audio buffer
|
||||
*/
|
||||
export function createTrackFromBuffer(
|
||||
buffer: AudioBuffer,
|
||||
name?: string,
|
||||
color?: TrackColor
|
||||
): Track {
|
||||
const track = createTrack(name, color);
|
||||
track.audioBuffer = buffer;
|
||||
return track;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mix multiple tracks into a single stereo buffer
|
||||
*/
|
||||
export function mixTracks(
|
||||
tracks: Track[],
|
||||
sampleRate: number,
|
||||
duration: number
|
||||
): AudioBuffer {
|
||||
// Determine the length needed
|
||||
const length = Math.ceil(duration * sampleRate);
|
||||
|
||||
// Create output buffer (stereo)
|
||||
const offlineContext = new OfflineAudioContext(2, length, sampleRate);
|
||||
const outputBuffer = offlineContext.createBuffer(2, length, sampleRate);
|
||||
|
||||
const leftChannel = outputBuffer.getChannelData(0);
|
||||
const rightChannel = outputBuffer.getChannelData(1);
|
||||
|
||||
// Check if any tracks are soloed
|
||||
const soloedTracks = tracks.filter((t) => t.solo && !t.mute);
|
||||
const audibleTracks = soloedTracks.length > 0 ? soloedTracks : tracks.filter((t) => !t.mute);
|
||||
|
||||
// Mix each audible track
|
||||
for (const track of audibleTracks) {
|
||||
if (!track.audioBuffer) continue;
|
||||
|
||||
const buffer = track.audioBuffer;
|
||||
const trackLength = Math.min(buffer.length, length);
|
||||
|
||||
// Get source channels (handle mono/stereo)
|
||||
const sourceLeft = buffer.getChannelData(0);
|
||||
const sourceRight = buffer.numberOfChannels > 1 ? buffer.getChannelData(1) : sourceLeft;
|
||||
|
||||
// Calculate pan gains (constant power panning)
|
||||
const panAngle = (track.pan * Math.PI) / 4; // -π/4 to π/4
|
||||
const leftGain = Math.cos(panAngle + Math.PI / 4) * track.volume;
|
||||
const rightGain = Math.sin(panAngle + Math.PI / 4) * track.volume;
|
||||
|
||||
// Mix into output buffer
|
||||
for (let i = 0; i < trackLength; i++) {
|
||||
leftChannel[i] += sourceLeft[i] * leftGain;
|
||||
rightChannel[i] += sourceRight[i] * rightGain;
|
||||
}
|
||||
}
|
||||
|
||||
return outputBuffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the maximum duration across all tracks
|
||||
*/
|
||||
export function getMaxTrackDuration(tracks: Track[]): number {
|
||||
let maxDuration = 0;
|
||||
|
||||
for (const track of tracks) {
|
||||
if (track.audioBuffer) {
|
||||
const duration = track.audioBuffer.duration;
|
||||
if (duration > maxDuration) {
|
||||
maxDuration = duration;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return maxDuration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate track mix gain (considering solo/mute)
|
||||
*/
|
||||
export function getTrackGain(track: Track, allTracks: Track[]): number {
|
||||
// If track is muted, gain is 0
|
||||
if (track.mute) return 0;
|
||||
|
||||
// Check if any tracks are soloed
|
||||
const hasSoloedTracks = allTracks.some((t) => t.solo);
|
||||
|
||||
// If there are soloed tracks and this track is not soloed, gain is 0
|
||||
if (hasSoloedTracks && !track.solo) return 0;
|
||||
|
||||
// Otherwise, return the track's volume
|
||||
return track.volume;
|
||||
}
|
||||
98
lib/hooks/useMultiTrack.ts
Normal file
98
lib/hooks/useMultiTrack.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import type { Track } from '@/types/track';
|
||||
import { createTrack, createTrackFromBuffer } from '@/lib/audio/track-utils';
|
||||
|
||||
const STORAGE_KEY = 'audio-ui-multi-track';
|
||||
|
||||
export function useMultiTrack() {
|
||||
const [tracks, setTracks] = useState<Track[]>(() => {
|
||||
if (typeof window === 'undefined') return [];
|
||||
|
||||
try {
|
||||
const saved = localStorage.getItem(STORAGE_KEY);
|
||||
if (saved) {
|
||||
const parsed = JSON.parse(saved);
|
||||
// Note: AudioBuffers can't be serialized, so we only restore track metadata
|
||||
return parsed.map((t: any) => ({
|
||||
...t,
|
||||
audioBuffer: null, // Will need to be reloaded
|
||||
}));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load tracks from localStorage:', error);
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
|
||||
// Save tracks to localStorage (without audio buffers)
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
try {
|
||||
const trackData = tracks.map((track) => ({
|
||||
...track,
|
||||
audioBuffer: null, // Don't serialize audio buffers
|
||||
}));
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(trackData));
|
||||
} catch (error) {
|
||||
console.error('Failed to save tracks to localStorage:', error);
|
||||
}
|
||||
}, [tracks]);
|
||||
|
||||
const addTrack = useCallback((name?: string) => {
|
||||
const track = createTrack(name);
|
||||
setTracks((prev) => [...prev, track]);
|
||||
return track;
|
||||
}, []);
|
||||
|
||||
const addTrackFromBuffer = useCallback((buffer: AudioBuffer, name?: string) => {
|
||||
const track = createTrackFromBuffer(buffer, name);
|
||||
setTracks((prev) => [...prev, track]);
|
||||
return track;
|
||||
}, []);
|
||||
|
||||
const removeTrack = useCallback((trackId: string) => {
|
||||
setTracks((prev) => prev.filter((t) => t.id !== trackId));
|
||||
}, []);
|
||||
|
||||
const updateTrack = useCallback((trackId: string, updates: Partial<Track>) => {
|
||||
setTracks((prev) =>
|
||||
prev.map((track) =>
|
||||
track.id === trackId ? { ...track, ...updates } : track
|
||||
)
|
||||
);
|
||||
}, []);
|
||||
|
||||
const clearTracks = useCallback(() => {
|
||||
setTracks([]);
|
||||
}, []);
|
||||
|
||||
const reorderTracks = useCallback((fromIndex: number, toIndex: number) => {
|
||||
setTracks((prev) => {
|
||||
const newTracks = [...prev];
|
||||
const [movedTrack] = newTracks.splice(fromIndex, 1);
|
||||
newTracks.splice(toIndex, 0, movedTrack);
|
||||
return newTracks;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const setTrackBuffer = useCallback((trackId: string, buffer: AudioBuffer) => {
|
||||
setTracks((prev) =>
|
||||
prev.map((track) =>
|
||||
track.id === trackId ? { ...track, audioBuffer: buffer } : track
|
||||
)
|
||||
);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
tracks,
|
||||
addTrack,
|
||||
addTrackFromBuffer,
|
||||
removeTrack,
|
||||
updateTrack,
|
||||
clearTracks,
|
||||
reorderTracks,
|
||||
setTrackBuffer,
|
||||
};
|
||||
}
|
||||
55
types/track.ts
Normal file
55
types/track.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Multi-track types and interfaces
|
||||
*/
|
||||
|
||||
export interface Track {
|
||||
id: string;
|
||||
name: string;
|
||||
color: string;
|
||||
height: number;
|
||||
audioBuffer: AudioBuffer | null;
|
||||
|
||||
// Track controls
|
||||
volume: number; // 0-1
|
||||
pan: number; // -1 (left) to 1 (right)
|
||||
mute: boolean;
|
||||
solo: boolean;
|
||||
recordEnabled: boolean;
|
||||
|
||||
// UI state
|
||||
collapsed: boolean;
|
||||
selected: boolean;
|
||||
}
|
||||
|
||||
export interface TrackState {
|
||||
tracks: Track[];
|
||||
selectedTrackId: string | null;
|
||||
soloedTracks: Set<string>;
|
||||
}
|
||||
|
||||
export type TrackColor =
|
||||
| 'red'
|
||||
| 'orange'
|
||||
| 'yellow'
|
||||
| 'green'
|
||||
| 'blue'
|
||||
| 'indigo'
|
||||
| 'purple'
|
||||
| 'pink'
|
||||
| 'gray';
|
||||
|
||||
export const TRACK_COLORS: Record<TrackColor, string> = {
|
||||
red: 'rgb(239, 68, 68)',
|
||||
orange: 'rgb(249, 115, 22)',
|
||||
yellow: 'rgb(234, 179, 8)',
|
||||
green: 'rgb(34, 197, 94)',
|
||||
blue: 'rgb(59, 130, 246)',
|
||||
indigo: 'rgb(99, 102, 241)',
|
||||
purple: 'rgb(168, 85, 247)',
|
||||
pink: 'rgb(236, 72, 153)',
|
||||
gray: 'rgb(156, 163, 175)',
|
||||
};
|
||||
|
||||
export const DEFAULT_TRACK_HEIGHT = 120;
|
||||
export const MIN_TRACK_HEIGHT = 60;
|
||||
export const MAX_TRACK_HEIGHT = 300;
|
||||
Reference in New Issue
Block a user