This commit is contained in:
Andras Schmelczer 2026-05-21 07:43:10 +01:00
commit 6bc125be1c
104 changed files with 3084 additions and 2410 deletions

1
.gitignore vendored
View file

@ -1,2 +1,3 @@
node_modules node_modules
dist dist
test-results

View file

@ -171,3 +171,57 @@ test('keeps audio focus outlines scoped to the active control', async ({ page })
await expect(volumeSlider).toHaveCSS('outline-style', 'solid'); await expect(volumeSlider).toHaveCSS('outline-style', 'solid');
await expect(volumeSlider).toHaveCSS('outline-offset', '-4px'); await expect(volumeSlider).toHaveCSS('outline-offset', '-4px');
}); });
test('keeps the config overlay scrollable and dismissible on mobile', async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 640 });
await page.goto('/');
const startButton = page.getByRole('button', { name: 'Start' });
await expect(startButton).toBeEnabled({ timeout: 30_000 });
await startButton.click();
await expect(page.locator('body')).not.toHaveClass(/is-loading/, {
timeout: 30_000,
});
const settingsButton = page.locator('button.settings');
await settingsButton.click();
const pane = page.locator('.config-pane');
const closeButton = page.locator('.config-pane-close');
await expect(pane).toBeVisible();
await expect(closeButton).toBeVisible();
const paneMetrics = await pane.evaluate((element) => {
const rect = element.getBoundingClientRect();
const style = window.getComputedStyle(element);
return {
bottom: rect.bottom,
clientHeight: element.clientHeight,
overflowY: style.overflowY,
scrollHeight: element.scrollHeight,
top: rect.top,
viewportHeight: window.innerHeight,
viewportWidth: window.innerWidth,
width: rect.width,
};
});
expect(paneMetrics.top).toBeGreaterThanOrEqual(0);
expect(paneMetrics.bottom).toBeLessThanOrEqual(paneMetrics.viewportHeight);
expect(Math.round(paneMetrics.width)).toBe(Math.round(paneMetrics.viewportWidth * 0.8));
expect(paneMetrics.scrollHeight).toBeGreaterThan(paneMetrics.clientHeight);
expect(['auto', 'scroll']).toContain(paneMetrics.overflowY);
await pane.evaluate((element) => {
element.scrollTop = element.scrollHeight;
});
await expect
.poll(() => pane.evaluate((element) => element.scrollTop))
.toBeGreaterThan(0);
await closeButton.click();
await expect(pane).toBeHidden();
await expect(settingsButton).toHaveAttribute('aria-expanded', 'false');
});

View file

@ -7,24 +7,64 @@
content="width=device-width,initial-scale=1,viewport-fit=cover" content="width=device-width,initial-scale=1,viewport-fit=cover"
/> />
<meta name="theme-color" content="#10151f" /> <meta name="theme-color" content="#10151f" />
<meta name="robots" content="index,follow" />
<meta name="author" content="Andras Schmelczer" />
<meta <meta
name="description" name="description"
content="Fleeting Garden is a joyful WebGPU drawing garden where your coloured paths bloom into moving organic trails." content="Tend it while you can. The garden returns to weather either way. A WebGPU drawing toy in your browser."
/> />
<link rel="canonical" href="https://schmelczer.dev/fleeting/" />
<meta property="og:title" content="Fleeting Garden" /> <meta property="og:title" content="Fleeting Garden" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Fleeting Garden" />
<meta property="og:locale" content="en_US" />
<meta <meta
property="og:description" property="og:description"
content="Pick a vibe, draw coloured paths, and watch them grow into a living WebGPU garden." content="Tend it while you can. The garden returns to weather either way. A WebGPU drawing toy in your browser."
/> />
<meta property="og:url" content="https://schmelczer.dev" /> <meta property="og:url" content="https://schmelczer.dev/fleeting/" />
<meta property="og:image" content="https://schmelczer.dev/og-image.jpg" /> <meta property="og:image" content="https://schmelczer.dev/fleeting/og-image.jpg" />
<meta property="og:image:width" content="1920" /> <meta property="og:image:type" content="image/jpeg" />
<meta property="og:image:height" content="1920" /> <meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:image:alt" content="Fleeting Garden social preview image." />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Fleeting Garden" />
<meta
name="twitter:description"
content="Tend it while you can. The garden returns to weather either way. A WebGPU drawing toy in your browser."
/>
<meta name="twitter:image" content="https://schmelczer.dev/fleeting/og-image.jpg" />
<meta name="twitter:image:alt" content="Fleeting Garden social preview image." />
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "WebApplication",
"name": "Fleeting Garden",
"url": "https://schmelczer.dev/fleeting/",
"description": "Tend it while you can. The garden returns to weather either way. A WebGPU drawing toy in your browser.",
"image": "https://schmelczer.dev/fleeting/og-image.jpg",
"applicationCategory": "DesignApplication",
"operatingSystem": "Any",
"browserRequirements": "Requires a browser with WebGPU support.",
"author": {
"@type": "Person",
"name": "Andras Schmelczer"
},
"sameAs": "https://github.com/schmelczer/webgpu"
}
</script>
<link rel="icon" type="image/svg+xml" href="favicon.svg" /> <link rel="icon" type="image/svg+xml" href="favicon.svg" />
<link rel="apple-touch-icon" href="apple-touch-icon-180x180.png" /> <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon-180x180.png" />
<link rel="manifest" href="manifest.webmanifest" /> <link rel="manifest" href="manifest.webmanifest" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="Fleeting Garden" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<title>Fleeting Garden</title> <title>Fleeting Garden</title>
</head> </head>
@ -43,6 +83,7 @@
to paint coloured paths, then use the toolbar to change colours, erase, export, to paint coloured paths, then use the toolbar to change colours, erase, export,
adjust the config overlay, restart, or open more information. adjust the config overlay, restart, or open more information.
</p> </p>
<div class="garden-grain" aria-hidden="true"></div>
<div class="eraser-preview" aria-hidden="true"></div> <div class="eraser-preview" aria-hidden="true"></div>
<div class="garden-prompt" aria-live="polite"></div> <div class="garden-prompt" aria-live="polite"></div>
@ -50,7 +91,7 @@
<div class="splash"> <div class="splash">
<h1 class="splash-title">Fleeting Garden</h1> <h1 class="splash-title">Fleeting Garden</h1>
<p class="splash-description"> <p class="splash-description">
Draw coloured paths and watch them bloom into a living WebGPU garden. Tend it while you can. The garden returns to weather either way.
</p> </p>
<button class="start-button" type="button" disabled>Start</button> <button class="start-button" type="button" disabled>Start</button>
</div> </div>
@ -85,22 +126,24 @@
<section> <section>
<h1>Fleeting Garden</h1> <h1>Fleeting Garden</h1>
<p> <p>
A living sketchpad where each stroke becomes a trail that agents follow, A garden is what we tend; the wild is what we get the moment we look away.
branch from, and weave into the scene. Both happen here at once. Your strokes plant colour, small agents follow them,
branch off, and slowly rewrite the patch you laid down into something you
didn't quite plan.
</p> </p>
<p> <p>
Paint with the three colour swatches, carve space with the eraser, and raise Three swatches plant the line. The eraser carves a clearing. The mirror folds
the mirror control when you want radial patterns instead of a single line. one gesture into many, like footpaths around a hidden well.
</p> </p>
<p> <p>
Switch vibes to recolour the whole garden without clearing your drawing. Add Switch vibes to change the season; your shapes stay, the light moves. Add or
or mute the generated piano, restart for a blank canvas, or export the current quiet the piano. Restart when you want a fresh field. Take a snapshot if you
frame as an internal buffer snapshot. want to keep one particular instant of weather.
</p> </p>
<p> <p>
Built with WebGPU and running locally in your browser. Source on Built with WebGPU, running locally in your browser. More of my work at
<a href="https://github.com/schmelczer/webgpu" target="_blank" rel="noopener" <a href="https://schmelczer.dev" target="_blank" rel="noopener"
>GitHub</a >schmelczer.dev</a
>. >.
</p> </p>
</section> </section>

View file

@ -3,7 +3,7 @@
"version": "0.2.0", "version": "0.2.0",
"private": true, "private": true,
"type": "module", "type": "module",
"description": "A WebGPU drawing garden where coloured paths grow into organic agent trails.", "description": "Tend it while you can. The garden returns to weather either way. A WebGPU drawing toy in your browser.",
"scripts": { "scripts": {
"dev": "vite --host 0.0.0.0", "dev": "vite --host 0.0.0.0",
"build": "vite build", "build": "vite build",

View file

@ -1,8 +1,9 @@
{ {
"name": "Fleeting Garden", "name": "Fleeting Garden",
"short_name": "Garden", "short_name": "Garden",
"description": "A joyful WebGPU drawing garden where coloured paths grow into organic agent trails.", "description": "Tend it while you can. The garden returns to weather either way. A WebGPU drawing toy in your browser.",
"start_url": "./", "start_url": "./",
"scope": "./",
"display": "fullscreen", "display": "fullscreen",
"background_color": "#10151f", "background_color": "#10151f",
"theme_color": "#10151f", "theme_color": "#10151f",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Before After
Before After

4
public/robots.txt Normal file
View file

@ -0,0 +1,4 @@
User-agent: *
Allow: /
Sitemap: https://schmelczer.dev/fleeting/sitemap.xml

6
public/sitemap.xml Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://schmelczer.dev/fleeting/</loc>
</url>
</urlset>

View file

@ -1,4 +1,4 @@
import { DEFAULT_AUDIO_VOLUME } from '../app-constants'; import { DEFAULT_AUDIO_VOLUME } from '../consts';
import type { PianoNoteRole } from './garden-audio-types'; import type { PianoNoteRole } from './garden-audio-types';
export interface GardenAudioChord { export interface GardenAudioChord {

View file

@ -38,6 +38,7 @@ export class GardenAudio {
private stopPianoAt: number | null = null; private stopPianoAt: number | null = null;
private lastEraserAt = Number.NEGATIVE_INFINITY; private lastEraserAt = Number.NEGATIVE_INFINITY;
private lastVibeStingerAt = Number.NEGATIVE_INFINITY; private lastVibeStingerAt = Number.NEGATIVE_INFINITY;
private startRequestId = 0;
public constructor(private readonly config: GardenAudioConfig) { public constructor(private readonly config: GardenAudioConfig) {
this.masterVolume = clamp01(config.masterVolume); this.masterVolume = clamp01(config.masterVolume);
@ -56,6 +57,14 @@ export class GardenAudio {
return; return;
} }
if (
this.lifecycle === 'started' &&
this.currentVibeId === vibe.id &&
this.graph.context?.state === 'running'
) {
return;
}
const context = this.graph.ensureContext(isUserGesture); const context = this.graph.ensureContext(isUserGesture);
if (!context) { if (!context) {
return; return;
@ -108,26 +117,50 @@ export class GardenAudio {
return; return;
} }
this.lifecycle = 'started'; const startRequestId = ++this.startRequestId;
this.applyVibe(vibe); void this.piano
this.pianoEngine.prime(context.currentTime, getVibeProfile(vibe)); .load(context)
this.graph.setMasterGain(this.masterVolume, startupRampSeconds);
const pianoLoad = this.piano.loadIfIdle(context);
if (pianoLoad) {
void pianoLoad
.then(() => { .then(() => {
if (this.graph.context === context && this.lifecycle !== 'destroyed') { if (!this.canCompleteStart(context, startRequestId)) {
this.pianoEngine.cue(context.currentTime, getVibeProfile(vibe)); return;
} }
this.activateStart(vibe, context, startupRampSeconds, true);
}) })
.catch((error) => { .catch((error) => {
if (this.canCompleteStart(context, startRequestId)) {
this.activateStart(vibe, context, startupRampSeconds, false);
}
ErrorHandler.addException(error, { ErrorHandler.addException(error, {
fallbackMessage: 'Could not load piano samples. Using synthesized audio.', fallbackMessage: 'Could not load piano samples.',
severity: Severity.WARNING, severity: Severity.WARNING,
}); });
}); });
} }
private canCompleteStart(context: AudioContext, startRequestId: number): boolean {
return (
this.graph.context === context &&
this.lifecycle !== 'destroyed' &&
!this.isMuted &&
this.startRequestId === startRequestId
);
}
private activateStart(
vibe: VibePreset,
context: AudioContext,
startupRampSeconds: number,
cuePiano: boolean
): void {
this.lifecycle = 'started';
this.currentVibeId = vibe.id;
this.graph.applyDelayProfile();
this.graph.setMasterGain(this.masterVolume, startupRampSeconds);
if (cuePiano) {
this.pianoEngine.cue(context.currentTime, getVibeProfile(vibe));
}
} }
public changeVibe(vibe: VibePreset, options: { userGesture?: boolean } = {}): void { public changeVibe(vibe: VibePreset, options: { userGesture?: boolean } = {}): void {

View file

@ -46,13 +46,6 @@ const degreeToSemitone = (profile: GardenAudioVibeProfile, degree: number): numb
type GardenAudioStyleIndex = 0 | 1 | 2; type GardenAudioStyleIndex = 0 | 1 | 2;
interface TouchDownRequest {
vibe: VibePreset;
now: number;
strength: number;
maniaAmount?: number;
}
interface PitchCandidate { interface PitchCandidate {
midi: number; midi: number;
preference: number; preference: number;
@ -152,7 +145,12 @@ export class GenerativePianoEngine {
now, now,
strength, strength,
maniaAmount = 0, maniaAmount = 0,
}: TouchDownRequest): void { }: {
vibe: VibePreset;
now: number;
strength: number;
maniaAmount?: number;
}): void {
const normalizedStrength = clamp01(strength); const normalizedStrength = clamp01(strength);
const normalizedManiaAmount = clamp01(maniaAmount); const normalizedManiaAmount = clamp01(maniaAmount);
const styleIndex = this.getStyleIndex(now); const styleIndex = this.getStyleIndex(now);

View file

@ -21,9 +21,6 @@ const pianoSamplerTuning = {
minDurationSeconds: 0.08, minDurationSeconds: 0.08,
minFadeSeconds: 0.08, minFadeSeconds: 0.08,
minGain: 0.0001, minGain: 0.0001,
synthGainScale: 0.34,
synthMaxDurationSeconds: 1.8,
synthOscillatorType: 'triangle' as OscillatorType,
tailStopExtraSeconds: 0.05, tailStopExtraSeconds: 0.05,
voiceStealFadeSeconds: 0.025, voiceStealFadeSeconds: 0.025,
voiceStealStopSeconds: 0.05, voiceStealStopSeconds: 0.05,
@ -39,9 +36,9 @@ export class PianoSampler {
private readonly graph: GardenAudioGraph private readonly graph: GardenAudioGraph
) {} ) {}
public loadIfIdle(context: BaseAudioContext): Promise<void> | null { public load(context: BaseAudioContext): Promise<void> {
if (this.loadState !== 'idle') { if (this.loadState === 'loaded') {
return null; return Promise.resolve();
} }
const loadedSamples = getLoadedPianoSamples(); const loadedSamples = getLoadedPianoSamples();
@ -80,14 +77,16 @@ export class PianoSampler {
return; return;
} }
const sample = this.findNearestSample(midi);
if (!sample) {
return;
}
const scheduledStart = Math.max( const scheduledStart = Math.max(
context.currentTime + PIANO_SCHEDULE_AHEAD_SECONDS, context.currentTime + PIANO_SCHEDULE_AHEAD_SECONDS,
startTime startTime
); );
const noteVelocity = clamp01(velocity); const noteVelocity = clamp01(velocity);
const sample = this.findNearestSample(midi);
if (sample) {
const noteGainValue = this.computeNoteGain(noteVelocity); const noteGainValue = this.computeNoteGain(noteVelocity);
const sustainSeconds = const sustainSeconds =
profileSustainSeconds * profileSustainSeconds *
@ -137,47 +136,6 @@ export class PianoSampler {
); );
}, },
}); });
return;
}
const noteGainValue = this.computeNoteGain(
noteVelocity,
pianoSamplerTuning.synthGainScale
);
const releaseAt =
scheduledStart +
clamp(
durationSeconds + profileSustainSeconds * 0.5,
pianoSamplerTuning.minDurationSeconds,
pianoSamplerTuning.synthMaxDurationSeconds
);
const stopAt = releaseAt + this.config.piano.releaseSeconds;
const source = context.createOscillator();
source.type = pianoSamplerTuning.synthOscillatorType;
source.frequency.setValueAtTime(getMidiFrequency(midi), scheduledStart);
this.scheduleVoice({
source,
scheduledStart,
stopAt,
pan,
lowpassHz,
delaySend,
eventBus,
configureGainEnvelope: (gain) => {
gain.gain.setValueAtTime(pianoSamplerTuning.minGain, scheduledStart);
gain.gain.exponentialRampToValueAtTime(
noteGainValue,
scheduledStart + this.config.piano.gainAttackSeconds
);
gain.gain.setTargetAtTime(
pianoSamplerTuning.minGain,
releaseAt,
this.config.piano.releaseSeconds
);
},
});
} }
public stopAll(): void { public stopAll(): void {
@ -312,6 +270,3 @@ export class PianoSampler {
this.samples = samples.slice().sort((a, b) => a.midi - b.midi); this.samples = samples.slice().sort((a, b) => a.midi - b.midi);
} }
} }
const getMidiFrequency = (midi: number): number =>
440 * Math.pow(2, (midi - 69) / PITCH_SEMITONES_PER_OCTAVE);

View file

@ -1,7 +1,38 @@
import type { LoadedPianoSample } from './garden-audio-types'; import type { LoadedPianoSample } from './garden-audio-types';
import a0SampleUrl from './samples/A0v12.m4a?url&no-inline';
import a1SampleUrl from './samples/A1v12.m4a?url&no-inline';
import a2SampleUrl from './samples/A2v12.m4a?url&no-inline';
import a3SampleUrl from './samples/A3v12.m4a?url&no-inline';
import a4SampleUrl from './samples/A4v12.m4a?url&no-inline';
import a5SampleUrl from './samples/A5v12.m4a?url&no-inline';
import a6SampleUrl from './samples/A6v12.m4a?url&no-inline';
import a7SampleUrl from './samples/A7v12.m4a?url&no-inline';
import c1SampleUrl from './samples/C1v12.m4a?url&no-inline';
import c2SampleUrl from './samples/C2v12.m4a?url&no-inline';
import c3SampleUrl from './samples/C3v12.m4a?url&no-inline';
import c4SampleUrl from './samples/C4v12.m4a?url&no-inline';
import c5SampleUrl from './samples/C5v12.m4a?url&no-inline';
import c6SampleUrl from './samples/C6v12.m4a?url&no-inline';
import c7SampleUrl from './samples/C7v12.m4a?url&no-inline';
import c8SampleUrl from './samples/C8v12.m4a?url&no-inline';
import dSharp1SampleUrl from './samples/Dsharp1v12.m4a?url&no-inline';
import dSharp2SampleUrl from './samples/Dsharp2v12.m4a?url&no-inline';
import dSharp3SampleUrl from './samples/Dsharp3v12.m4a?url&no-inline';
import dSharp4SampleUrl from './samples/Dsharp4v12.m4a?url&no-inline';
import dSharp5SampleUrl from './samples/Dsharp5v12.m4a?url&no-inline';
import dSharp6SampleUrl from './samples/Dsharp6v12.m4a?url&no-inline';
import dSharp7SampleUrl from './samples/Dsharp7v12.m4a?url&no-inline';
import fSharp1SampleUrl from './samples/Fsharp1v12.m4a?url&no-inline';
import fSharp2SampleUrl from './samples/Fsharp2v12.m4a?url&no-inline';
import fSharp3SampleUrl from './samples/Fsharp3v12.m4a?url&no-inline';
import fSharp4SampleUrl from './samples/Fsharp4v12.m4a?url&no-inline';
import fSharp5SampleUrl from './samples/Fsharp5v12.m4a?url&no-inline';
import fSharp6SampleUrl from './samples/Fsharp6v12.m4a?url&no-inline';
import fSharp7SampleUrl from './samples/Fsharp7v12.m4a?url&no-inline';
interface PianoSampleDefinition { interface PianoSampleDefinition {
midi: number; midi: number;
path: string;
url: string; url: string;
} }
@ -10,48 +41,39 @@ export interface PianoSampleLoadProgress {
totalCount: number; totalCount: number;
} }
const sampleFiles: Array<[fileName: string, midi: number]> = [ const pianoSampleDefinitions: Array<PianoSampleDefinition> = [
['A0v12.m4a', 21], { url: a0SampleUrl, path: './samples/A0v12.m4a', midi: 21 },
['C1v12.m4a', 24], { url: c1SampleUrl, path: './samples/C1v12.m4a', midi: 24 },
['Dsharp1v12.m4a', 27], { url: dSharp1SampleUrl, path: './samples/Dsharp1v12.m4a', midi: 27 },
['Fsharp1v12.m4a', 30], { url: fSharp1SampleUrl, path: './samples/Fsharp1v12.m4a', midi: 30 },
['A1v12.m4a', 33], { url: a1SampleUrl, path: './samples/A1v12.m4a', midi: 33 },
['C2v12.m4a', 36], { url: c2SampleUrl, path: './samples/C2v12.m4a', midi: 36 },
['Dsharp2v12.m4a', 39], { url: dSharp2SampleUrl, path: './samples/Dsharp2v12.m4a', midi: 39 },
['Fsharp2v12.m4a', 42], { url: fSharp2SampleUrl, path: './samples/Fsharp2v12.m4a', midi: 42 },
['A2v12.m4a', 45], { url: a2SampleUrl, path: './samples/A2v12.m4a', midi: 45 },
['C3v12.m4a', 48], { url: c3SampleUrl, path: './samples/C3v12.m4a', midi: 48 },
['Dsharp3v12.m4a', 51], { url: dSharp3SampleUrl, path: './samples/Dsharp3v12.m4a', midi: 51 },
['Fsharp3v12.m4a', 54], { url: fSharp3SampleUrl, path: './samples/Fsharp3v12.m4a', midi: 54 },
['A3v12.m4a', 57], { url: a3SampleUrl, path: './samples/A3v12.m4a', midi: 57 },
['C4v12.m4a', 60], { url: c4SampleUrl, path: './samples/C4v12.m4a', midi: 60 },
['Dsharp4v12.m4a', 63], { url: dSharp4SampleUrl, path: './samples/Dsharp4v12.m4a', midi: 63 },
['Fsharp4v12.m4a', 66], { url: fSharp4SampleUrl, path: './samples/Fsharp4v12.m4a', midi: 66 },
['A4v12.m4a', 69], { url: a4SampleUrl, path: './samples/A4v12.m4a', midi: 69 },
['C5v12.m4a', 72], { url: c5SampleUrl, path: './samples/C5v12.m4a', midi: 72 },
['Dsharp5v12.m4a', 75], { url: dSharp5SampleUrl, path: './samples/Dsharp5v12.m4a', midi: 75 },
['Fsharp5v12.m4a', 78], { url: fSharp5SampleUrl, path: './samples/Fsharp5v12.m4a', midi: 78 },
['A5v12.m4a', 81], { url: a5SampleUrl, path: './samples/A5v12.m4a', midi: 81 },
['C6v12.m4a', 84], { url: c6SampleUrl, path: './samples/C6v12.m4a', midi: 84 },
['Dsharp6v12.m4a', 87], { url: dSharp6SampleUrl, path: './samples/Dsharp6v12.m4a', midi: 87 },
['Fsharp6v12.m4a', 90], { url: fSharp6SampleUrl, path: './samples/Fsharp6v12.m4a', midi: 90 },
['A6v12.m4a', 93], { url: a6SampleUrl, path: './samples/A6v12.m4a', midi: 93 },
['C7v12.m4a', 96], { url: c7SampleUrl, path: './samples/C7v12.m4a', midi: 96 },
['Dsharp7v12.m4a', 99], { url: dSharp7SampleUrl, path: './samples/Dsharp7v12.m4a', midi: 99 },
['Fsharp7v12.m4a', 102], { url: fSharp7SampleUrl, path: './samples/Fsharp7v12.m4a', midi: 102 },
['A7v12.m4a', 105], { url: a7SampleUrl, path: './samples/A7v12.m4a', midi: 105 },
['C8v12.m4a', 108], { url: c8SampleUrl, path: './samples/C8v12.m4a', midi: 108 },
]; ];
const sampleBaseUrl = `${import.meta.env.BASE_URL}audio/`;
const pianoSampleDefinitions: Array<PianoSampleDefinition> = sampleFiles
.map(([fileName, midi]) => ({
midi,
url: `${sampleBaseUrl}${fileName}`,
}))
.sort((a, b) => a.midi - b.midi);
let loadedPianoSamples: Array<LoadedPianoSample> | null = null; let loadedPianoSamples: Array<LoadedPianoSample> | null = null;
let pianoSampleLoadPromise: Promise<Array<LoadedPianoSample>> | null = null; let pianoSampleLoadPromise: Promise<Array<LoadedPianoSample>> | null = null;
@ -111,11 +133,11 @@ export const loadPianoSamples = (
} }
).then( ).then(
(samples) => { (samples) => {
loadedPianoSamples = samples loadedPianoSamples = samples.sort((a, b) => a.midi - b.midi);
.filter((sample): sample is LoadedPianoSample => sample !== null) if (loadedPianoSamples.length !== pianoSampleDefinitions.length) {
.sort((a, b) => a.midi - b.midi); throw new Error(
if (loadedPianoSamples.length === 0) { `Loaded ${loadedPianoSamples.length}/${pianoSampleDefinitions.length} piano samples.`
throw new Error('Unable to load any piano samples.'); );
} }
return [...loadedPianoSamples]; return [...loadedPianoSamples];
}, },
@ -138,7 +160,7 @@ const loadPianoSample = async (
): Promise<LoadedPianoSample> => { ): Promise<LoadedPianoSample> => {
const response = await fetch(sample.url, { signal }); const response = await fetch(sample.url, { signal });
if (!response.ok) { if (!response.ok) {
throw new Error(`Unable to load piano sample ${sample.url}`); throw new Error(`Unable to load piano sample ${sample.path}`);
} }
const audioData = await response.arrayBuffer(); const audioData = await response.arrayBuffer();
@ -148,17 +170,13 @@ const loadPianoSample = async (
const loadPianoSampleBatch = async ( const loadPianoSampleBatch = async (
samples: Array<PianoSampleDefinition>, samples: Array<PianoSampleDefinition>,
loadSample: ( loadSample: (sample: PianoSampleDefinition) => Promise<LoadedPianoSample>
sample: PianoSampleDefinition ): Promise<Array<LoadedPianoSample>> => {
) => Promise<LoadedPianoSample | null> const results: Array<LoadedPianoSample> = [];
): Promise<Array<LoadedPianoSample | null>> => {
const results: Array<LoadedPianoSample | null> = [];
for (let index = 0; index < samples.length; index += sampleLoadTuning.concurrency) { for (let index = 0; index < samples.length; index += sampleLoadTuning.concurrency) {
const batch = samples.slice(index, index + sampleLoadTuning.concurrency); const batch = samples.slice(index, index + sampleLoadTuning.concurrency);
const batchResults = await Promise.all( const batchResults = await Promise.all(batch.map((sample) => loadSample(sample)));
batch.map((sample) => loadSample(sample).catch(() => null))
);
results.push(...batchResults); results.push(...batchResults);
} }

Some files were not shown because too many files have changed in this diff Show more