Build BeatHound sequencer app
This commit is contained in:
1 parent
226ababcf1
commit
e23825cdb1
49 files changed
+6455
-2
No files matched your search
@@ -0,0 +1,124 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { AudioEngine } from '../audio/AudioEngine';
|
||||
import {
|
||||
getPlaybackTickDurationMs,
|
||||
PLAYBACK_SUBSTEPS_PER_STEP,
|
||||
} from '../domain/sequencer';
|
||||
import type { BeatPoint } from '../domain/sequencer';
|
||||
|
||||
interface UseBeatPlaybackOptions {
|
||||
beats: readonly BeatPoint[];
|
||||
tempoBpm: number;
|
||||
totalSteps: number;
|
||||
}
|
||||
|
||||
export interface BeatPlayback {
|
||||
currentStep: number;
|
||||
isPlaying: boolean;
|
||||
isStarting: boolean;
|
||||
audioError: string | null;
|
||||
togglePlayback: () => Promise<void>;
|
||||
resetPlayback: () => void;
|
||||
}
|
||||
|
||||
export function useBeatPlayback({
|
||||
beats,
|
||||
tempoBpm,
|
||||
totalSteps,
|
||||
}: UseBeatPlaybackOptions): BeatPlayback {
|
||||
const [currentStep, setCurrentStep] = useState(-1);
|
||||
const [isPlaying, setIsPlaying] = useState(false);
|
||||
const [isStarting, setIsStarting] = useState(false);
|
||||
const [audioError, setAudioError] = useState<string | null>(null);
|
||||
|
||||
const audioEngineRef = useRef<AudioEngine | null>(null);
|
||||
const beatsRef = useRef(beats);
|
||||
const totalStepsRef = useRef(totalSteps);
|
||||
const nextPlaybackTickRef = useRef(0);
|
||||
|
||||
if (audioEngineRef.current === null) audioEngineRef.current = new AudioEngine();
|
||||
beatsRef.current = beats;
|
||||
totalStepsRef.current = totalSteps;
|
||||
|
||||
const advanceStep = useCallback(() => {
|
||||
const totalPlaybackTicks = totalStepsRef.current * PLAYBACK_SUBSTEPS_PER_STEP;
|
||||
const playbackTick = nextPlaybackTickRef.current % totalPlaybackTicks;
|
||||
const step = playbackTick / PLAYBACK_SUBSTEPS_PER_STEP;
|
||||
|
||||
setCurrentStep(step);
|
||||
beatsRef.current.forEach((beat) => {
|
||||
if (beat.step >= totalStepsRef.current) return;
|
||||
const beatTick = Math.round(beat.step * PLAYBACK_SUBSTEPS_PER_STEP) % totalPlaybackTicks;
|
||||
if (beatTick === playbackTick) audioEngineRef.current?.play(beat.soundId);
|
||||
});
|
||||
|
||||
nextPlaybackTickRef.current = (playbackTick + 1) % totalPlaybackTicks;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPlaying) {
|
||||
setCurrentStep(-1);
|
||||
nextPlaybackTickRef.current = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
advanceStep();
|
||||
}, [isPlaying, advanceStep]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPlaying) return undefined;
|
||||
|
||||
const interval = window.setInterval(
|
||||
advanceStep,
|
||||
getPlaybackTickDurationMs(tempoBpm),
|
||||
);
|
||||
return () => window.clearInterval(interval);
|
||||
}, [isPlaying, tempoBpm, advanceStep]);
|
||||
|
||||
useEffect(() => {
|
||||
if (beats.length === 0 && isPlaying) setIsPlaying(false);
|
||||
}, [beats.length, isPlaying]);
|
||||
|
||||
useEffect(() => {
|
||||
nextPlaybackTickRef.current %= totalSteps * PLAYBACK_SUBSTEPS_PER_STEP;
|
||||
setCurrentStep((step) => (step >= totalSteps ? step % totalSteps : step));
|
||||
}, [totalSteps]);
|
||||
|
||||
useEffect(() => () => {
|
||||
void audioEngineRef.current?.dispose();
|
||||
}, []);
|
||||
|
||||
const togglePlayback = useCallback(async () => {
|
||||
if (isPlaying) {
|
||||
setIsPlaying(false);
|
||||
return;
|
||||
}
|
||||
if (beats.length === 0 || isStarting) return;
|
||||
|
||||
setIsStarting(true);
|
||||
setAudioError(null);
|
||||
try {
|
||||
await audioEngineRef.current?.start();
|
||||
setIsPlaying(true);
|
||||
} catch {
|
||||
setAudioError('Audio could not start. Check your browser audio settings and try again.');
|
||||
} finally {
|
||||
setIsStarting(false);
|
||||
}
|
||||
}, [beats.length, isPlaying, isStarting]);
|
||||
|
||||
const resetPlayback = useCallback(() => {
|
||||
nextPlaybackTickRef.current = 0;
|
||||
setCurrentStep(-1);
|
||||
setAudioError(null);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
currentStep,
|
||||
isPlaying,
|
||||
isStarting,
|
||||
audioError,
|
||||
togglePlayback,
|
||||
resetPlayback,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useCallback, useMemo, useReducer, useRef } from 'react';
|
||||
import type { BeatTemplate } from '../domain/beatTemplates';
|
||||
import {
|
||||
getNextAvailableStep,
|
||||
getTotalSteps,
|
||||
} from '../domain/sequencer';
|
||||
import type { BeatsPerBar } from '../domain/sequencer';
|
||||
import type { BeatPoint } from '../domain/sequencer';
|
||||
import type { SoundId } from '../domain/sounds';
|
||||
import { createInitialSequencerState, sequencerReducer } from '../domain/sequencerReducer';
|
||||
import { useBeatPlayback } from './useBeatPlayback';
|
||||
|
||||
export interface BeatSequencer {
|
||||
beats: BeatPoint[];
|
||||
currentStep: number;
|
||||
isPlaying: boolean;
|
||||
isStarting: boolean;
|
||||
audioError: string | null;
|
||||
tempoBpm: number;
|
||||
beatsPerBar: BeatsPerBar;
|
||||
totalSteps: number;
|
||||
focusedSoundId: SoundId | null;
|
||||
selectedBeat: BeatPoint | undefined;
|
||||
addBeat: (soundId: SoundId) => void;
|
||||
moveBeat: (beatId: string, step: number) => void;
|
||||
selectBeat: (beatId: string) => void;
|
||||
selectSound: (soundId: SoundId) => void;
|
||||
removeSelectedBeat: () => void;
|
||||
removeFocusedSound: () => void;
|
||||
setTempoBpm: (tempoBpm: number) => void;
|
||||
setBeatsPerBar: (beatsPerBar: BeatsPerBar) => void;
|
||||
loadTemplate: (template: BeatTemplate) => void;
|
||||
togglePlayback: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function useBeatSequencer(): BeatSequencer {
|
||||
const [state, dispatch] = useReducer(
|
||||
sequencerReducer,
|
||||
undefined,
|
||||
createInitialSequencerState,
|
||||
);
|
||||
const { beats, beatsPerBar, focusedSoundId, selectedBeatId, tempoBpm } = state;
|
||||
const totalSteps = getTotalSteps(beatsPerBar);
|
||||
|
||||
const nextBeatIdRef = useRef(1);
|
||||
|
||||
const visibleBeats = useMemo(
|
||||
() => beats.filter((beat) => beat.step < totalSteps),
|
||||
[beats, totalSteps],
|
||||
);
|
||||
const selectedBeat = useMemo(
|
||||
() => visibleBeats.find((beat) => beat.id === selectedBeatId),
|
||||
[selectedBeatId, visibleBeats],
|
||||
);
|
||||
const playback = useBeatPlayback({ beats: visibleBeats, tempoBpm, totalSteps });
|
||||
const resetPlayback = playback.resetPlayback;
|
||||
|
||||
const addBeat = useCallback((soundId: SoundId): void => {
|
||||
const beat: BeatPoint = {
|
||||
id: `beat-${nextBeatIdRef.current}`,
|
||||
soundId,
|
||||
step: getNextAvailableStep(beats, totalSteps),
|
||||
};
|
||||
nextBeatIdRef.current += 1;
|
||||
dispatch({ type: 'beat-added', beat });
|
||||
}, [beats, totalSteps]);
|
||||
|
||||
const moveBeat = useCallback((beatId: string, step: number): void => {
|
||||
dispatch({ type: 'beat-moved', beatId, step });
|
||||
}, []);
|
||||
|
||||
const selectBeat = useCallback((beatId: string): void => {
|
||||
dispatch({ type: 'beat-selected', beatId });
|
||||
}, []);
|
||||
|
||||
const selectSound = useCallback((soundId: SoundId): void => {
|
||||
dispatch({ type: 'sound-selected', soundId });
|
||||
}, []);
|
||||
|
||||
const removeSelectedBeat = useCallback((): void => {
|
||||
dispatch({ type: 'selected-beat-removed' });
|
||||
}, []);
|
||||
|
||||
const removeFocusedSound = useCallback((): void => {
|
||||
dispatch({ type: 'focused-sound-removed' });
|
||||
}, []);
|
||||
|
||||
const setTempoBpm = useCallback((tempo: number): void => {
|
||||
dispatch({ type: 'tempo-changed', tempoBpm: tempo });
|
||||
}, []);
|
||||
|
||||
const setBeatsPerBar = useCallback((nextBeatsPerBar: BeatsPerBar): void => {
|
||||
dispatch({ type: 'time-signature-changed', beatsPerBar: nextBeatsPerBar });
|
||||
}, []);
|
||||
|
||||
const loadTemplate = useCallback((template: BeatTemplate): void => {
|
||||
const templateBeats: BeatPoint[] = template.beats.map((templateBeat) => {
|
||||
const beat: BeatPoint = {
|
||||
id: `beat-${nextBeatIdRef.current}`,
|
||||
...templateBeat,
|
||||
};
|
||||
nextBeatIdRef.current += 1;
|
||||
return beat;
|
||||
});
|
||||
|
||||
dispatch({
|
||||
type: 'template-loaded',
|
||||
beats: templateBeats,
|
||||
tempoBpm: template.tempoBpm,
|
||||
beatsPerBar: template.beatsPerBar,
|
||||
});
|
||||
resetPlayback();
|
||||
}, [resetPlayback]);
|
||||
|
||||
return {
|
||||
beats: visibleBeats,
|
||||
currentStep: playback.currentStep,
|
||||
isPlaying: playback.isPlaying,
|
||||
isStarting: playback.isStarting,
|
||||
audioError: playback.audioError,
|
||||
tempoBpm,
|
||||
beatsPerBar,
|
||||
totalSteps,
|
||||
focusedSoundId,
|
||||
selectedBeat,
|
||||
addBeat,
|
||||
moveBeat,
|
||||
selectBeat,
|
||||
selectSound,
|
||||
removeSelectedBeat,
|
||||
removeFocusedSound,
|
||||
setTempoBpm,
|
||||
setBeatsPerBar,
|
||||
loadTemplate,
|
||||
togglePlayback: playback.togglePlayback,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useCallback } from 'react';
|
||||
import type { BeatTemplate } from '../domain/beatTemplates';
|
||||
import type { SoundId } from '../domain/sounds';
|
||||
import type { BeatSequencer } from './useBeatSequencer';
|
||||
import { useBeatSequencer } from './useBeatSequencer';
|
||||
import type { SoundPalette } from './useSoundPalette';
|
||||
import { useSoundPalette } from './useSoundPalette';
|
||||
|
||||
export interface BeatStudio {
|
||||
sequencer: BeatSequencer;
|
||||
soundPalette: SoundPalette;
|
||||
addSound: (soundId: SoundId) => void;
|
||||
applyTemplate: (template: BeatTemplate) => void;
|
||||
}
|
||||
|
||||
export function useBeatStudio(): BeatStudio {
|
||||
const sequencer = useBeatSequencer();
|
||||
const soundPalette = useSoundPalette();
|
||||
const { addBeat, loadTemplate } = sequencer;
|
||||
const { activateSounds } = soundPalette;
|
||||
|
||||
const addSound = useCallback((soundId: SoundId): void => {
|
||||
activateSounds([soundId]);
|
||||
addBeat(soundId);
|
||||
}, [activateSounds, addBeat]);
|
||||
|
||||
const applyTemplate = useCallback((template: BeatTemplate): void => {
|
||||
loadTemplate(template);
|
||||
activateSounds(template.beats.map((beat) => beat.soundId));
|
||||
}, [activateSounds, loadTemplate]);
|
||||
|
||||
return { sequencer, soundPalette, addSound, applyTemplate };
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
export interface PopoverDisclosure {
|
||||
isOpen: boolean;
|
||||
onDidPresent: () => void;
|
||||
onDidDismiss: () => void;
|
||||
}
|
||||
|
||||
export function usePopoverDisclosure(): PopoverDisclosure {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
const onDidPresent = useCallback(() => setIsOpen(true), []);
|
||||
const onDidDismiss = useCallback(() => setIsOpen(false), []);
|
||||
|
||||
return { isOpen, onDidPresent, onDidDismiss };
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import type { SoundId } from '../domain/sounds';
|
||||
import { generateUniqueSoundColor } from '../domain/soundColors';
|
||||
|
||||
export interface PaletteSound {
|
||||
id: SoundId;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export interface SoundPalette {
|
||||
activeSounds: PaletteSound[];
|
||||
colorBySoundId: Partial<Record<SoundId, string>>;
|
||||
activateSounds: (soundIds: readonly SoundId[]) => void;
|
||||
}
|
||||
|
||||
export function useSoundPalette(): SoundPalette {
|
||||
const [activeSounds, setActiveSounds] = useState<PaletteSound[]>([]);
|
||||
|
||||
const activateSounds = useCallback((soundIds: readonly SoundId[]): void => {
|
||||
setActiveSounds((currentSounds) => {
|
||||
const nextSounds = [...currentSounds];
|
||||
const currentCount = nextSounds.length;
|
||||
soundIds.forEach((soundId) => {
|
||||
if (nextSounds.some((sound) => sound.id === soundId)) return;
|
||||
|
||||
nextSounds.push({
|
||||
id: soundId,
|
||||
color: generateUniqueSoundColor(nextSounds.map((sound) => sound.color)),
|
||||
});
|
||||
});
|
||||
return nextSounds.length === currentCount ? currentSounds : nextSounds;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const colorBySoundId = useMemo(() => {
|
||||
const colors: Partial<Record<SoundId, string>> = {};
|
||||
activeSounds.forEach((sound) => {
|
||||
colors[sound.id] = sound.color;
|
||||
});
|
||||
return colors;
|
||||
}, [activeSounds]);
|
||||
|
||||
return { activeSounds, colorBySoundId, activateSounds };
|
||||
}
|
||||
Reference in new issue
Block a user