Play sounds as notes of an instrument asset #331
game-maker / suite (push) Failing after 2m40s
game-maker / gate (push) Successful in 3m14s

A sound could only be played as it was, one at a time. An instrument
is a node graph that makes a note a sound: Notes nodes bring the note
in, Samples play sound assets for it, the effects of a sound FX shape
it and the Output sums the layers. Its tab plays it from a keyboard,
a behavior with Play note. It is what patterns and songs (#330) will
play.

- New asset type instrument, under the heading Music, not placeable.
  A new one starts as Notes into a Sample into the Output.
- Notes are counted as MIDI does: 60 is C4, names like C#4, sharps
  only, the lowest C-1. Notes has From and To, outputs any, note,
  frequency and velocity, and with Single notes a trigger per note,
  each with an optional name for a drum kit.
- New port type trigger, only into the trigger of a source. Inputs
  can take any number of edges now (PortDef.many): a trigger, and
  the Output, which plays everything into it side by side.
- Sample plays a sound asset. Follow note shifts it by note - root
  through the pitch worklet of #317, so it keeps its length. Gate
  fades it out at the end of the note, One-shot plays through. Loop
  runs between Loop start and Loop end, also in the worklet.
- Parameters declares the instrument's own parameters with a
  default. Sound FX sends the sound through a sound FX asset, its
  parameters as inputs, the sound set in where its Input was.
- compileInstrument walks the graph once per note. A trigger is on
  only for the notes it stands for, a silent source silences what it
  alone feeds, a Mix with a silent side is the other side. velocity
  and the parameters stay open for the voice. Builds are cached per
  note until the graph or a sound or FX it names changes.
- The player takes a note as one voice of several layers, each way
  with its own file and volume. release fades the gated ways out,
  one-shots play on. playNote can release after a duration.
- Play note plays one note with velocity, volume, duration and
  detached, and hands out voice for Set sound FX parameters and
  Stop sound. Velocity is always loudness. Instrument parameters
  picks values for the instrument's parameters like Sound FX
  parameters does for an FX, renames follow.
- The tab has the graph, a header field per parameter, Stop, and
  128 keys below. Keys without sound are grey. A key plays while it
  is held. Focused, the computer keyboard plays as in a tracker by
  KeyboardEvent.code, the arrows move the octave.

Findings:
- A label of the keys set fill on the shared small text style and
  darkened every small label of the editor. Caught in a screenshot
  before the commit, the keys have a style of their own now.
- Suite task 523 on cf6799a failed two checks of e2e 34 that timed
  audio by the page's clock: a 2.95 s echo tail was gone after 1 s,
  and Quad in was further along than 0.7 s allow. Both time on the
  audio clock now through a new hook __gm.sound.clock().

Tests:
- instrument.test.ts (new, 22): notes, asset, palette, round trip,
  compile per note, drum kit, zones, Mix, velocity and parameters,
  Sound FX node with rename, problems, cache, Play note, the keys
- sound-library +7 (layers, release, duration, early release, loop
  region in buffer and worklet), pitch-player +2 (loop region),
  node-catalog +4, graph adjusted. 582 tests in the touched files.
- e2e 4 and 34 on melektaus-atx: ALL PASSED, 34 with 44 checks (+7)
- Gate on melektaus-atx: CHECK EXIT 0, 243 test files, 3750 tests
- Counter-checks: any always on, release ending one-shots, Sound FX
  inputs ignored, loop region ignored. 3, 2, 1 and 1 tests failed.
- Browser probe on stein2: keys, held key, Single notes names and
  the header looked at in screenshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-06 10:07:40 +02:00
1 parent cf6799a784
commit 8a4e4a6762
54 files changed
+2561 -143

No files matched your search

+320
View File
@@ -0,0 +1,320 @@
import { graphEmitter } from '../graph/emitGraph';
import { type DeclaredPort, type Graph, graphFingerprint, type GraphNode } from '../graph/Graph';
import type { GraphLookup } from '../graph/lookup';
import { resolveDef, terminalNode } from '../graph/nested';
import { inlineValue, type NodeDef } from '../graph/NodeRegistry';
import { asNumber } from '../graph/values';
import type { InstrumentAsset } from '../model/Asset';
import { graphLookup } from '../model/graphLookup';
import { textOf } from '../model/Properties';
import { findAssetOf, type Project } from '../model/Project';
import { resolveAssetProps } from '../properties/resolve';
import { volumeOf } from '../properties/sounds';
import { soundFxBuildFor } from '../soundfx/compile';
import {
type FxAmount,
type FxPlan,
type FxStagePlan,
isSoundFxNodeDef,
SOUND_FX_INPUT,
SOUND_FX_OUTPUT,
SoundFxMix,
type SoundFxNodeDef,
withPitch,
withStages,
} from '../soundfx/nodes';
import {
INSTRUMENT_NOTES,
INSTRUMENT_OUTPUT,
INSTRUMENT_PARAMETERS,
INSTRUMENT_SAMPLE,
INSTRUMENT_SOUND_FX,
isInstrumentNodeDef,
noteOutputKey,
noteParam,
notesRange,
singleNotes,
VELOCITY_PARAM,
} from './nodes';
import { MIDDLE_C, noteFrequency } from './notes';
/**
* What an instrument's graph reaches outside itself: the sounds its Samples play and the sound FX
* its Sound FX nodes send them through. `key` changes whenever one of them does, so a cached note is
* compiled again when the sound or the FX it was made of is edited.
*/
export interface InstrumentSources {
lookup: GraphLookup;
sound(assetId: string): { file: string; volume: number } | null;
soundFx(assetId: string): FxPlan | null;
key(assetId: string): string;
}
export function instrumentSourcesOf(project: Project): InstrumentSources {
return {
lookup: graphLookup(project),
sound: (assetId) => {
const asset = findAssetOf(project, assetId, 'sound');
return asset ? { file: asset.file, volume: volumeOf(resolveAssetProps(project, asset)) } : null;
},
soundFx: (assetId) => {
const asset = findAssetOf(project, assetId, 'soundfx');
return asset ? soundFxBuildFor(asset).compiled : null;
},
key: (assetId) => {
const sound = findAssetOf(project, assetId, 'sound');
if (sound) return `${sound.file}@${volumeOf(resolveAssetProps(project, sound))}`;
const fx = findAssetOf(project, assetId, 'soundfx');
return fx ? graphFingerprint(fx.graph) : '';
},
};
}
export interface InstrumentBuild {
/** What the note is made of, each played on its own and summed; empty is silence. */
layers: readonly FxPlan[];
/** Per node id, what keeps the graph from compiling. */
problems: Record<string, string>;
/** One line for the tab: empty once compiled. */
reason: string;
}
/**
* What travels along an edge of an instrument: sounds (none where nothing plays for this note, more
* than one only into the Output), a number, or whether a trigger is on for this note.
*/
type Value = { plans: FxPlan[] } | { amount: FxAmount } | { on: boolean };
const SILENT: Value = { plans: [] };
type Def = SoundFxNodeDef | (NodeDef & { instrument: true });
function isInstrumentDef(def: NodeDef): def is Def {
if (isInstrumentNodeDef(def)) return true;
return isSoundFxNodeDef(def) && def.type !== SOUND_FX_INPUT && def.type !== SOUND_FX_OUTPUT;
}
/** The parameters the Parameters node declares, in their order, each with its default. */
export function instrumentParams(graph: Graph): readonly DeclaredPort[] {
return terminalNode(graph, INSTRUMENT_PARAMETERS)?.ports ?? [];
}
/**
* One note of an instrument (#331): the graph walked back from the Output, with the triggers that
* stand for this note on and every other one off. A source whose trigger is off is silence, and so
* is everything it alone feeds; a Mix with one silent side is its other side. `note` and `frequency`
* are numbers here, `velocity` and the parameters stay open for every voice to fill in.
*/
export function compileInstrument(graph: Graph, note: number, sources: InstrumentSources): InstrumentBuild {
const walk = graphEmitter<Def, Value>(graph, {
isDef: isInstrumentDef,
noun: 'instrument',
resolve: (node, def) =>
def.derivePorts ? ((resolveDef(node, graph, sources.lookup) as Def | undefined) ?? def) : def,
emit: (def, inputs, node) => emitNode(def, inputs, node),
unfed: (node, port) => {
if (port.type === 'number') return { amount: { value: asNumber(inlineValue(node, port)) } };
if (port.type === 'audio' && port.many) return SILENT;
walk.problem(
node,
port.type === 'trigger'
? 'Nothing triggers it: connect it to a Notes node'
: 'Nothing comes in: connect it to a Sample',
);
return null;
},
conform: (node, port, value) => {
const fits =
port.type === 'audio'
? 'plans' in value
: port.type === 'trigger'
? 'on' in value
: 'amount' in value;
if (fits) return value;
walk.problem(
node,
`"${port.label}" takes ${port.type === 'audio' ? 'a sound' : port.type === 'trigger' ? 'a trigger' : 'a number'}`,
);
return null;
},
gather: (_node, port, values) =>
port.type === 'trigger'
? { on: values.some((v) => 'on' in v && v.on) }
: { plans: values.flatMap((v) => ('plans' in v ? v.plans : [])) },
});
function emitNode(def: Def, inputs: Record<string, Value>, node: GraphNode): Record<string, Value> {
const plansAt = (key: string) => {
const value = inputs[key];
return value && 'plans' in value ? value.plans : [];
};
const amounts: Record<string, FxAmount> = {};
for (const [key, value] of Object.entries(inputs)) if ('amount' in value) amounts[key] = value.amount;
switch (node.type) {
case INSTRUMENT_NOTES:
return notesOutputs(node, note);
case INSTRUMENT_PARAMETERS:
return Object.fromEntries(
(node.ports ?? []).map((port) => [
port.key,
{ amount: { value: port.default ?? 0, param: port.key } },
]),
);
case INSTRUMENT_SAMPLE: {
const plan = sampleOf(node, note);
const trigger = inputs.trigger;
return { out: plan && trigger && 'on' in trigger && trigger.on ? { plans: [plan] } : SILENT };
}
case INSTRUMENT_SOUND_FX: {
const fx = sources.soundFx(textOf(node.params.fx ?? ''));
const arriving = plansAt('in');
return { out: { plans: fx ? arriving.map((plan) => throughFx(fx, plan, amounts)) : arriving } };
}
case INSTRUMENT_OUTPUT:
return { out: { plans: plansAt('in') } };
}
if (!isSoundFxNodeDef(def)) return {};
if (def.type === SoundFxMix.type) {
const [a] = plansAt('a');
const [b] = plansAt('b');
if (!a || !b) return { out: { plans: a ? [a] : b ? [b] : [] } };
return { out: { plans: [def.emit({ a, b }, amounts, node.params)] } };
}
const [arriving] = plansAt('in');
return { out: arriving ? { plans: [def.emit({ in: arriving }, amounts, node.params)] } : SILENT };
}
/** A Sample's sound, or null after saying why it has none – also where its trigger is off. */
function sampleOf(node: GraphNode, played: number): FxPlan | null {
const id = textOf(node.params.sound ?? '');
const sound = id ? sources.sound(id) : null;
if (!id) walk.problem(node, 'No sound picked');
else if (!sound) walk.problem(node, 'That sound is gone');
else if (!sound.file) walk.problem(node, 'The sound has no file');
if (!sound?.file) return null;
const follows = node.params.followNote !== false;
const shift = follows ? played - noteParam(node.params, 'root', MIDDLE_C) : 0;
const loop = node.params.loop === true;
return {
pitch: shift === 0 ? [] : [{ value: shift }],
stages: [],
source: {
file: sound.file,
volume: sound.volume,
loop,
loopStart: loop ? Math.max(0, asNumber(node.params.loopStart ?? 0)) : 0,
loopEnd: loop ? Math.max(0, asNumber(node.params.loopEnd ?? 0)) : 0,
gate: textOf(node.params.mode ?? 'gate') !== 'oneshot',
},
};
}
const output = graph.nodes.find((n) => n.type === INSTRUMENT_OUTPUT);
if (!output) return { layers: [], problems: walk.problems, reason: 'No Output node' };
const arrived = walk.input(output, { key: 'in', label: 'in', type: 'audio', many: true });
const failed = walk.firstProblem();
if (failed !== null || !arrived || !('plans' in arrived))
return { layers: [], problems: walk.problems, reason: failed ?? 'Cannot compile' };
return { layers: arrived.plans, problems: walk.problems, reason: '' };
}
/** The outputs of a Notes node for one note: its triggers, and the note as numbers. */
function notesOutputs(node: GraphNode, note: number): Record<string, Value> {
const { from, to } = notesRange(node.params);
const inside = note >= from && note <= to;
const outputs: Record<string, Value> = {
any: { on: inside },
note: { amount: { value: note } },
frequency: { amount: { value: noteFrequency(note) } },
velocity: { amount: { value: 1, param: VELOCITY_PARAM, min: 0, max: 1 } },
};
if (singleNotes(node.params))
for (let at = from; at <= to; at++) outputs[noteOutputKey(at)] = { on: at === note };
return outputs;
}
/**
* A sound sent through a sound FX: the plan of the FX with the sound set in where its Input was, and
* each of its parameters bound to what arrives at the input of that name – held to the FX's row, as
* a value handed to the FX itself would be. One left open keeps its default.
*/
function throughFx(fx: FxPlan, sound: FxPlan, given: Readonly<Record<string, FxAmount>>): FxPlan {
const bind = (amount: FxAmount): FxAmount => {
if (amount.param === undefined) return amount;
const fed = given[amount.param];
if (!fed) return amount;
const value = Math.max(amount.min ?? -Infinity, Math.min(amount.max ?? Infinity, fed.value));
return fed.param === undefined
? { value }
: { value, param: fed.param, min: amount.min, max: amount.max };
};
const stages = fx.stages.map((stage) => bindStage(stage, bind));
if ('mix' in fx)
return {
mix: bind(fx.mix),
a: throughFx(fx.a, sound, given),
b: throughFx(fx.b, sound, given),
stages,
};
const pitched = fx.pitch.reduce((plan, semitones) => withPitch(plan, bind(semitones)), sound);
return withStages(pitched, stages);
}
function bindStage(stage: FxStagePlan, bind: (amount: FxAmount) => FxAmount): FxStagePlan {
if (stage.kind === 'gain') return { ...stage, db: bind(stage.db) };
if (stage.kind === 'filter') return { ...stage, gain: bind(stage.gain) };
return {
...stage,
time: bind(stage.time),
feedback: bind(stage.feedback),
damping: bind(stage.damping),
mix: bind(stage.mix),
};
}
const builds = new Map<string, { fingerprint: string; notes: Map<number, InstrumentBuild> }>();
/**
* One note of the asset, compiled again only when what it is made of has changed: the graph, or a
* sound or sound FX it names. A note is played far more often than its instrument is edited.
*/
export function instrumentBuildFor(
asset: InstrumentAsset,
note: number,
sources: InstrumentSources,
): InstrumentBuild {
const named = asset.graph.nodes
.map((node) => textOf(node.params[node.type === INSTRUMENT_SOUND_FX ? 'fx' : 'sound'] ?? ''))
.filter((id) => id !== '');
const fingerprint = `${graphFingerprint(asset.graph)}|${named.map((id) => sources.key(id)).join('|')}`;
let cached = builds.get(asset.id);
if (!cached || cached.fingerprint !== fingerprint) {
cached = { fingerprint, notes: new Map() };
builds.set(asset.id, cached);
}
let build = cached.notes.get(note);
if (!build) {
build = compileInstrument(asset.graph, note, sources);
cached.notes.set(note, build);
}
return build;
}
/**
* The instrument's problems, the same for every note: the walk from the Output reaches every node
* whatever is played, only the triggers differ.
*/
export function instrumentCheck(asset: InstrumentAsset, sources: InstrumentSources): InstrumentBuild {
return instrumentBuildFor(asset, MIDDLE_C, sources);
}
/** Which notes of the keyboard make a sound at all: those inside a Notes node's range. */
export function playedNotes(graph: Graph): Set<number> {
const notes = new Set<number>();
for (const node of graph.nodes) {
if (node.type !== INSTRUMENT_NOTES) continue;
const { from, to } = notesRange(node.params);
for (let note = from; note <= to; note++) notes.add(note);
}
return notes;
}
+246
View File
@@ -0,0 +1,246 @@
import type { DeclaredPort, Graph } from '../graph/Graph';
import { newId } from '../ids';
import {
INSTRUMENT_NOTES,
INSTRUMENT_OUTPUT,
INSTRUMENT_PARAMETERS,
INSTRUMENT_SAMPLE,
INSTRUMENT_SOUND_FX,
} from '../graph/nested';
import type { NodeDef, PortDef } from '../graph/NodeRegistry';
import { type PropertyBag, textOf } from '../model/Properties';
import type { PropertyDef } from '../properties/PropertySchema';
import { soundFxParamPort } from '../soundfx/nodes';
import { HIGHEST_NOTE, heldNote, LOWEST_NOTE, MIDDLE_C, NOTE_OPTIONS, noteName } from './notes';
export { INSTRUMENT_NOTES, INSTRUMENT_OUTPUT, INSTRUMENT_PARAMETERS, INSTRUMENT_SAMPLE, INSTRUMENT_SOUND_FX };
/**
* A node only an instrument's graph has (#331). Like a sound FX node it never runs: the instrument's
* compiler (`compile.ts`) reads what it stands for, once per note.
*/
export interface InstrumentNodeDef extends NodeDef {
category: 'sound';
instrument: true;
}
export function isInstrumentNodeDef(def: NodeDef): def is InstrumentNodeDef {
return def.category === 'sound' && 'instrument' in def;
}
/**
* The value of an instrument's `velocity` while its voice is open: not a name a parameter can have,
* so it never meets one, and a `Set sound FX parameters` cannot reach it by accident.
*/
export const VELOCITY_PARAM = '@velocity';
const triggerIn: PortDef = { key: 'trigger', label: 'trigger', type: 'trigger', many: true };
const audioIn: PortDef = { key: 'in', label: 'in', type: 'audio' };
const audioOut: PortDef = { key: 'out', label: 'out', type: 'audio' };
function noteRow(key: string, label: string, note: number): PropertyDef {
return { key, label, kind: 'enum', default: String(note), options: NOTE_OPTIONS };
}
/** A note setting as a number, held to the keyboard. */
export function noteParam(params: PropertyBag, key: string, fallback: number): number {
const text = textOf(params[key] ?? '');
return text === '' ? fallback : heldNote(Number(text));
}
const FROM = noteRow('from', 'From', MIDDLE_C);
const TO = noteRow('to', 'To', MIDDLE_C + 11);
const SINGLE = { key: 'singleNotes', label: 'Single notes', kind: 'boolean' as const, default: false };
/** Where a note's own name is kept: `name60` for C4. */
export const noteNameKey = (note: number) => `name${note}`;
/** The output a single note leaves through: `n60` for C4, whatever it is called. */
export const noteOutputKey = (note: number) => `n${note}`;
const NAME_ROWS: PropertyDef[] = Array.from({ length: HIGHEST_NOTE - LOWEST_NOTE + 1 }, (_, i) => ({
key: noteNameKey(LOWEST_NOTE + i),
label: `Name of ${noteName(LOWEST_NOTE + i)}`,
kind: 'text',
default: '',
}));
const NAME_KEYS = NAME_ROWS.map((row) => row.key);
/** The lowest and the highest note of a Notes node, whichever way round they were picked. */
export function notesRange(params: PropertyBag): { from: number; to: number } {
const a = noteParam(params, FROM.key, MIDDLE_C);
const b = noteParam(params, TO.key, MIDDLE_C + 11);
return { from: Math.min(a, b), to: Math.max(a, b) };
}
export function singleNotes(params: PropertyBag): boolean {
return params[SINGLE.key] === true;
}
/** What a note is called on its output and in a piano roll: its own name, else its note name. */
export function noteLabel(params: PropertyBag, note: number): string {
return textOf(params[noteNameKey(note)] ?? '').trim() || noteName(note);
}
export const InstrumentNotes: InstrumentNodeDef = {
type: INSTRUMENT_NOTES,
label: 'Notes',
category: 'sound',
instrument: true,
description:
'Where the notes come in. "any" triggers what it is connected to for every note from "from" to "to"; "note" is the number of the note played (60 is C4), "frequency" its pitch in Hz and "velocity" how hard it is struck, 0 to 1. With "single notes" there is a trigger output for each note in the range as well, for a drum kit, each with a name of its own if you give it one. Several Notes nodes split the keyboard into zones; where two overlap, both play.',
inputs: [],
outputs: [
{ key: 'any', label: 'any', type: 'trigger' },
{ key: 'note', label: 'note', type: 'number' },
{ key: 'frequency', label: 'frequency', type: 'number' },
{ key: 'velocity', label: 'velocity', type: 'number' },
],
params: [FROM, TO, SINGLE, ...NAME_ROWS],
// The node shows the names on its outputs already.
hiddenParams: () => NAME_KEYS,
idleParams: (params) => {
if (!singleNotes(params)) return NAME_KEYS;
const { from, to } = notesRange(params);
return NAME_KEYS.filter((_, i) => LOWEST_NOTE + i < from || LOWEST_NOTE + i > to);
},
derivePorts: ({ node }) => {
if (!singleNotes(node.params)) return {};
const { from, to } = notesRange(node.params);
const outputs: PortDef[] = [];
for (let note = from; note <= to; note++)
outputs.push({ key: noteOutputKey(note), label: noteLabel(node.params, note), type: 'trigger' });
return { outputs };
},
};
const SOUND: PropertyDef = { key: 'sound', label: 'Sound', kind: 'sound', default: '' };
const ROOT = noteRow('root', 'Root', MIDDLE_C);
const FOLLOW = { key: 'followNote', label: 'Follow note', kind: 'boolean' as const, default: true };
export const SAMPLE_MODES = [
{ value: 'gate', label: 'Gate' },
{ value: 'oneshot', label: 'One-shot' },
];
const MODE: PropertyDef = {
key: 'mode',
label: 'Mode',
kind: 'enum',
default: 'gate',
options: SAMPLE_MODES,
};
const LOOP = { key: 'loop', label: 'Loop', kind: 'boolean' as const, default: false };
const LOOP_START: PropertyDef = {
key: 'loopStart',
label: 'Loop start (s)',
kind: 'number',
default: 0,
min: 0,
step: 0.01,
};
const LOOP_END: PropertyDef = {
key: 'loopEnd',
label: 'Loop end (s)',
kind: 'number',
default: 0,
min: 0,
step: 0.01,
};
export const InstrumentSample: InstrumentNodeDef = {
type: INSTRUMENT_SAMPLE,
label: 'Sample',
category: 'sound',
instrument: true,
description:
'Plays a sound asset when a note triggers it. With "follow note" it is played higher or lower by the distance from "root" – the note it sounds as it is – and keeps its length. Off, every note plays it as it is, as for a drum. "Gate" ends it with the note, faded out in a few milliseconds; "One-shot" plays it through whatever the note does. "Loop" repeats it, between "loop start" and "loop end" in seconds where they are set (0 is the end of the sound), until the note ends – or, as a one-shot, until it is stopped. The volume of the sound asset counts.',
inputs: [triggerIn],
outputs: [audioOut],
params: [SOUND, ROOT, FOLLOW, MODE, LOOP, LOOP_START, LOOP_END],
idleParams: (params) => [
...(params[FOLLOW.key] === false ? [ROOT.key] : []),
...(params[LOOP.key] === true ? [] : [LOOP_START.key, LOOP_END.key]),
],
};
export const InstrumentParameters: InstrumentNodeDef = {
type: INSTRUMENT_PARAMETERS,
label: 'Parameters',
category: 'sound',
instrument: true,
description:
'The parameters of the instrument: every one declared here is a number output with a default. A Play note can hand in other values through an Instrument parameters node, and a Set sound FX parameters can change them on a note while it plays.',
inputs: [],
outputs: [],
params: [],
declaresPorts: 'outputs',
portKinds: ['number'],
declaredPort: (port: DeclaredPort) => soundFxParamPort(port),
};
const FX: PropertyDef = { key: 'fx', label: 'Sound FX', kind: 'asset', default: '', assetTypes: ['soundfx'] };
export const InstrumentSoundFx: InstrumentNodeDef = {
type: INSTRUMENT_SOUND_FX,
label: 'Sound FX',
category: 'sound',
instrument: true,
description:
"Sends the sound through a sound FX asset, as if it were the sound at the FX's Input. Each parameter of the FX is an input here; one left open keeps the FX's default. A Mix in the FX plays the sound on both of its ways.",
inputs: [audioIn],
outputs: [audioOut],
params: [FX],
derivePorts: ({ node, lookup }) => {
const fx = lookup.soundFx(textOf(node.params[FX.key] ?? ''));
if (!fx) return {};
return {
label: fx.name,
inputs: fx.params.map((port) => ({
key: port.key,
label: port.key,
type: 'number' as const,
default: port.default ?? 0,
field: { key: port.key, label: port.key, kind: 'number' as const, default: port.default ?? 0 },
})),
};
},
};
export const InstrumentOutput: InstrumentNodeDef = {
type: INSTRUMENT_OUTPUT,
label: 'Output',
category: 'sound',
instrument: true,
description:
'What is heard of a note. It takes any number of sounds and plays them together – the layers of the instrument.',
inputs: [{ ...audioIn, many: true }],
outputs: [],
params: [],
};
export const INSTRUMENT_NODES: readonly InstrumentNodeDef[] = [
InstrumentNotes,
InstrumentSample,
InstrumentParameters,
InstrumentSoundFx,
InstrumentOutput,
];
/**
* What a new instrument starts as: every note of an octave from C4 plays one Sample, which waits for
* its sound to be picked.
*/
export function starterInstrumentGraph(): Graph {
const notes = newId();
const sample = newId();
const output = newId();
return {
nodes: [
{ id: notes, type: INSTRUMENT_NOTES, x: 0, y: 0, params: {} },
{ id: sample, type: INSTRUMENT_SAMPLE, x: 220, y: 0, params: {} },
{ id: output, type: INSTRUMENT_OUTPUT, x: 460, y: 0, params: {} },
],
edges: [
{ id: newId(), from: { node: notes, port: 'any' }, to: { node: sample, port: 'trigger' } },
{ id: newId(), from: { node: sample, port: 'out' }, to: { node: output, port: 'in' } },
],
};
}
+37
View File
@@ -0,0 +1,37 @@
/**
* Notes as an instrument counts them (#331): by number as MIDI does, 0 the lowest, 60 the middle C
* and 69 the A at 440 Hz. A name has the octave after it without a dash (`C4`, `C#4`), sharps only,
* so the lowest is `C-1`.
*/
export const LOWEST_NOTE = 0;
export const HIGHEST_NOTE = 127;
export const MIDDLE_C = 60;
const NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
export function noteName(note: number): string {
const n = Math.round(note);
return `${NAMES[((n % 12) + 12) % 12]}${Math.floor(n / 12) - 1}`;
}
/** The frequency of a note in Hz, a fractional one between its neighbours. */
export function noteFrequency(note: number): number {
return 440 * 2 ** ((note - 69) / 12);
}
/** A note as a whole number in range: what a pattern, a setting or a `Play note` hands in. */
export function heldNote(value: number): number {
if (!Number.isFinite(value)) return MIDDLE_C;
return Math.max(LOWEST_NOTE, Math.min(HIGHEST_NOTE, Math.round(value)));
}
/** Every note, for a setting that picks one by name. */
export const NOTE_OPTIONS: { value: string; label: string }[] = Array.from(
{ length: HIGHEST_NOTE - LOWEST_NOTE + 1 },
(_, i) => ({ value: String(LOWEST_NOTE + i), label: noteName(LOWEST_NOTE + i) }),
);
/** Whether a note is a black key. */
export function isSharp(note: number): boolean {
return NAMES[((Math.round(note) % 12) + 12) % 12]!.length > 1;
}