smplr 0.17.1 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -328,6 +328,200 @@ const piano = new SplendidGrandPiano(context, { storage });
328
328
 
329
329
  ⚠️ `CacheStorage` is based on [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache) and only works in secure environments that runs with `https`. Read your framework documentation for setup instructions. For example, in nextjs you can use https://www.npmjs.com/package/next-dev-https. For vite there's https://github.com/liuweiGL/vite-plugin-mkcert. Find the appropriate solution for your environment.
330
330
 
331
+ ## Sequencer
332
+
333
+ `Sequencer` schedules notes from one or more tracks against any smplr instrument with sample-accurate timing.
334
+
335
+ ```js
336
+ import { Sequencer, SplendidGrandPiano, DrumMachine } from "smplr";
337
+
338
+ const context = new AudioContext();
339
+ const piano = new SplendidGrandPiano(context);
340
+ const drums = new DrumMachine(context, { instrument: "TR-808" });
341
+
342
+ const seq = new Sequencer(context, { bpm: 120, loop: true });
343
+
344
+ seq.addTrack(piano, [
345
+ { note: "C4", at: "1:1", duration: "4n" },
346
+ { note: "E4", at: "1:2", duration: "4n" },
347
+ { note: "G4", at: "1:3", duration: "4n" },
348
+ { note: "C5", at: "1:4", duration: "2n" },
349
+ ]);
350
+
351
+ seq.addTrack(drums, [
352
+ { note: "kick", at: "1:1" },
353
+ { note: "snare", at: "1:2" },
354
+ { note: "kick", at: "1:3" },
355
+ { note: "snare", at: "1:4" },
356
+ ]);
357
+
358
+ seq.loopEnd = "2:1"; // 1 bar
359
+ seq.start();
360
+ ```
361
+
362
+ #### Time notation
363
+
364
+ Note positions and durations accept several formats:
365
+
366
+ | Format | Meaning |
367
+ | ---------- | ------------------------------ |
368
+ | `"4n"` | quarter note |
369
+ | `"8n"` | eighth note |
370
+ | `"4n."` | dotted quarter (1.5×) |
371
+ | `"1m"` | one measure |
372
+ | `"2:1"` | bar 2, beat 1 (1-indexed) |
373
+ | `"2:3:48"` | bar 2, beat 3, +48 ticks |
374
+ | `96` | raw ticks (number passthrough) |
375
+
376
+ #### Constructor options
377
+
378
+ ```js
379
+ const seq = new Sequencer(context, {
380
+ bpm: 120, // default 120
381
+ ppq: 480, // pulses per quarter note, default 480
382
+ timeSignature: 4, // beats per bar, default 4
383
+ loop: false, // default false
384
+ loopStart: 0, // loop start position (ticks or string)
385
+ loopEnd: "2:1", // loop end position; defaults to end of longest track
386
+ lookaheadMs: 200, // scheduling lookahead, default 200
387
+ intervalMs: 50, // flush interval, default 50
388
+ humanize: { timingMs: 10, velocity: 8 }, // optional randomisation
389
+ });
390
+ ```
391
+
392
+ #### Playback
393
+
394
+ ```js
395
+ seq.start(); // start from beginning (or resume from pause if no offset given)
396
+ seq.pause(); // freeze position
397
+ seq.stop(); // stop and reset to 0
398
+ seq.togglePlayPause(); // pause if playing, start/resume otherwise
399
+
400
+ seq.state; // "stopped" | "playing" | "paused"
401
+ ```
402
+
403
+ Individual sequenced notes can be stopped by their id:
404
+
405
+ ```js
406
+ seq.stopNote("intro-c"); // stop immediately
407
+ seq.stopNote("intro-c", time); // stop at a scheduled time
408
+ ```
409
+
410
+ #### Tempo and position
411
+
412
+ ```js
413
+ seq.bpm = 140; // change BPM live, no glitch
414
+ seq.timeSignature = 3; // change time signature
415
+
416
+ seq.position; // current position as "bar:beat:tick" string
417
+ seq.position = "3:1"; // seek while playing or stopped
418
+ ```
419
+
420
+ #### Loop
421
+
422
+ ```js
423
+ seq.loop = true;
424
+ seq.loopStart = "1:1"; // ticks or string notation
425
+ seq.loopEnd = "3:1"; // ticks or string notation
426
+
427
+ seq.progress; // 0..1 within the loop range
428
+ ```
429
+
430
+ #### Pattern API
431
+
432
+ `scheduleRepeat` fires a callback at a regular musical interval, passing the exact AudioContext time:
433
+
434
+ ```js
435
+ const cancel = seq.scheduleRepeat((time) => {
436
+ piano.start({ note: "C4", time, duration: 0.1 });
437
+ }, "8n"); // every eighth note
438
+
439
+ cancel(); // stop repeating
440
+ ```
441
+
442
+ An optional third argument sets the start position:
443
+
444
+ ```js
445
+ seq.scheduleRepeat(callback, "4n", "2:1"); // start at bar 2
446
+ ```
447
+
448
+ #### Events
449
+
450
+ ```js
451
+ seq.on("statechange", (state) => {
452
+ // state: "playing" | "paused" | "stopped"
453
+ setSeqState(state);
454
+ });
455
+
456
+ seq.on("beat", (beat, time) => {
457
+ const delay = (time - context.currentTime) * 1000;
458
+ setTimeout(() => metronome.flash(), delay);
459
+ });
460
+
461
+ seq.on("bar", (bar, time) => {
462
+ ui.updateBar(bar);
463
+ });
464
+ seq.on("loop", () => {
465
+ console.log("looped");
466
+ });
467
+ seq.on("end", () => {
468
+ console.log("done");
469
+ });
470
+ seq.on("start", () => {});
471
+ seq.on("stop", () => {});
472
+ seq.on("pause", () => {});
473
+
474
+ seq.off("beat", handler); // remove a listener
475
+ ```
476
+
477
+ #### Note events
478
+
479
+ `noteOn` and `noteOff` events fire when the instrument's `onStart` / `onEnded` callbacks are called, so they are driven by the actual audio playback — not by the scheduling lookahead.
480
+
481
+ ```js
482
+ seq.on("noteOn", (event) => {
483
+ console.log(event.noteId, event.trackIndex, event.noteIndex);
484
+ highlight(event.noteId);
485
+ });
486
+ seq.on("noteOff", (event) => {
487
+ unhighlight(event.noteId);
488
+ });
489
+ ```
490
+
491
+ The `event` object (`NoteEvent`) contains:
492
+
493
+ | Field | Type | Description |
494
+ | ------------ | ------------------ | ------------------------------------------------------ |
495
+ | `noteId` | `string \| number` | The note's `id` if provided, otherwise its array index |
496
+ | `trackIndex` | `number` | Index of the track in the order it was added |
497
+ | `noteIndex` | `number` | Index of the note within its track's notes array |
498
+ | `note` | `SequencerNote` | The original note object |
499
+
500
+ You can set a custom `id` on any `SequencerNote` to use as `noteId`:
501
+
502
+ ```js
503
+ seq.addTrack(piano, [
504
+ { id: "intro-c", note: "C4", at: "1:1", duration: "4n" },
505
+ { id: "intro-e", note: "E4", at: "1:2", duration: "4n" },
506
+ ]);
507
+ ```
508
+
509
+ #### Humanize
510
+
511
+ Add subtle randomisation to timing and velocity for a more natural feel:
512
+
513
+ ```js
514
+ const seq = new Sequencer(context, {
515
+ bpm: 90,
516
+ humanize: { timingMs: 12, velocity: 8 },
517
+ });
518
+ ```
519
+
520
+ - `timingMs`: maximum random offset in milliseconds (±). Default 0.
521
+ - `velocity`: maximum random offset in MIDI velocity units (±). Default 0.
522
+
523
+ ---
524
+
331
525
  ## Instruments
332
526
 
333
527
  ### Sampler
package/dist/index.d.mts CHANGED
@@ -122,7 +122,7 @@ type SmplrJson = {
122
122
  /**
123
123
  * A note event passed to Smplr.start(). Can be a full object, a note name, or a MIDI number.
124
124
  */
125
- type NoteEvent = {
125
+ type NoteEvent$1 = {
126
126
  note: string | number;
127
127
  velocity?: number;
128
128
  time?: number;
@@ -132,8 +132,8 @@ type NoteEvent = {
132
132
  loop?: boolean;
133
133
  ampRelease?: number;
134
134
  stopId?: string | number;
135
- onStart?: (event: NoteEvent) => void;
136
- onEnded?: (event: NoteEvent) => void;
135
+ onStart?: (event: NoteEvent$1) => void;
136
+ onEnded?: (event: NoteEvent$1) => void;
137
137
  } | string | number;
138
138
  /**
139
139
  * Target for Smplr.stop(). Can be a full object, a stopId, or a MIDI number.
@@ -199,7 +199,7 @@ declare class DrumMachine {
199
199
  getSampleNames(): string[];
200
200
  getGroupNames(): string[];
201
201
  getSampleNamesForGroup(groupName: string): string[];
202
- start(sample: NoteEvent): StopFn;
202
+ start(sample: NoteEvent$1): StopFn;
203
203
  stop(sample?: StopTarget): void;
204
204
  disconnect(): void;
205
205
  /** @deprecated */
@@ -218,6 +218,189 @@ declare class DrumMachine {
218
218
  */
219
219
  declare function drumMachineToSmplrJson(instrument: DrumMachineInstrument): SmplrJson;
220
220
 
221
+ /**
222
+ * TransportClock
223
+ *
224
+ * Converts between musical ticks and AudioContext time with support for:
225
+ * - BPM changes mid-playback (via checkpoints)
226
+ * - Pause / resume
227
+ * - Seek to arbitrary tick position
228
+ * - Loop restart (seekAt a future audio time)
229
+ *
230
+ * All time values are in AudioContext seconds (context.currentTime).
231
+ * Ticks are the internal unit: ppq ticks per quarter note.
232
+ *
233
+ * Principle: a Checkpoint records that at a specific audio time, a specific
234
+ * tick position was reached at a specific BPM. Checkpoints are always ordered
235
+ * by audioTime. The conversion functions find the last checkpoint whose
236
+ * audioTime (or tick) is <= the query value and interpolate from there.
237
+ */
238
+ type TransportState = "stopped" | "playing" | "paused";
239
+
240
+ type SequencerNote = {
241
+ /** Optional identifier for this note. Used as `noteId` in noteOn/noteOff events. Defaults to the note's array index. */
242
+ id?: string | number;
243
+ note: string | number;
244
+ /** Musical position: ticks, "4n", "1m", "2:1", "1:1.5", etc. */
245
+ at: string | number;
246
+ /** Note duration: ticks, "4n", "8n", etc. Omit for a one-shot trigger. */
247
+ duration?: string | number;
248
+ velocity?: number;
249
+ };
250
+ /**
251
+ * Any instrument the Sequencer can drive.
252
+ * Compatible with SplendidGrandPiano, DrumMachine, Smplr, and any object
253
+ * that has a `start()` method accepting note + optional scheduling params.
254
+ */
255
+ type SequencerInstrument = {
256
+ start(event: {
257
+ note: string | number;
258
+ time?: number;
259
+ duration?: number;
260
+ velocity?: number;
261
+ noteId?: string | number;
262
+ onStart?: (event: unknown) => void;
263
+ onEnded?: (event: unknown) => void;
264
+ }): unknown;
265
+ };
266
+ /** Emitted with "noteOn" and "noteOff" events. */
267
+ type NoteEvent = {
268
+ noteId: string | number;
269
+ trackIndex: number;
270
+ noteIndex: number;
271
+ note: SequencerNote;
272
+ };
273
+ type SequencerOptions = {
274
+ bpm?: number;
275
+ ppq?: number;
276
+ timeSignature?: number;
277
+ loop?: boolean;
278
+ loopStart?: string | number;
279
+ loopEnd?: string | number;
280
+ /** How far ahead (ms) to pre-schedule notes. Default 200. */
281
+ lookaheadMs?: number;
282
+ /** How often (ms) the flush loop runs. Default 50. */
283
+ intervalMs?: number;
284
+ /** Randomise timing (ms) and velocity per note for a human feel. */
285
+ humanize?: {
286
+ timingMs?: number;
287
+ velocity?: number;
288
+ };
289
+ };
290
+ declare class Sequencer {
291
+ private readonly _context;
292
+ private readonly _clock;
293
+ private readonly _ppq;
294
+ private _timeSignature;
295
+ private _tracks;
296
+ private _repeatEvents;
297
+ private _listeners;
298
+ private _loop;
299
+ private _loopStartTick;
300
+ /** null = default to _totalTicks */
301
+ private _loopEndOverride;
302
+ private _lookaheadSec;
303
+ private _intervalMs;
304
+ private _humanize;
305
+ private _intervalId;
306
+ /** AudioContext time high-water mark: notes up to here have been scheduled. */
307
+ private _scheduledThrough;
308
+ /** Computed from track notes; the tick where the last note ends. */
309
+ private _totalTicks;
310
+ /** Guards against scheduling the auto-stop setTimeout more than once. */
311
+ private _endScheduled;
312
+ /** Active voices keyed by noteId, so individual notes can be stopped. */
313
+ private _activeVoices;
314
+ constructor(context: BaseAudioContext, options?: SequencerOptions);
315
+ addTrack(instrument: SequencerInstrument, notes: SequencerNote[]): this;
316
+ removeTrack(instrument: SequencerInstrument): this;
317
+ clearTracks(): this;
318
+ get state(): TransportState;
319
+ /**
320
+ * Start playback from `offsetTick`, or resume from pause if no offset given.
321
+ */
322
+ start(offsetTick?: number): this;
323
+ pause(): this;
324
+ stop(): this;
325
+ /**
326
+ * Stop a single note that was scheduled by the sequencer.
327
+ * @param noteId The id of the note (from SequencerNote.id or auto-assigned index).
328
+ * @param time Optional AudioContext time to schedule the stop.
329
+ */
330
+ stopNote(noteId: string | number, time?: number): this;
331
+ /**
332
+ * Toggle between playing and paused. If stopped, starts from the beginning.
333
+ */
334
+ togglePlayPause(): this;
335
+ get bpm(): number;
336
+ set bpm(value: number);
337
+ get timeSignature(): number;
338
+ set timeSignature(value: number);
339
+ /** Current transport position as "bar:beat:tick" (1-indexed). */
340
+ get position(): string;
341
+ /**
342
+ * Seek to a position. Accepts ticks or any time string ("2:1", "4n", …).
343
+ * Works while playing (seamless) or stopped/paused.
344
+ */
345
+ set position(value: string | number);
346
+ get loop(): boolean;
347
+ set loop(value: boolean);
348
+ /** Loop start in ticks. */
349
+ get loopStart(): number;
350
+ set loopStart(value: string | number);
351
+ /** Loop end in ticks. Defaults to the end of the longest track. */
352
+ get loopEnd(): number;
353
+ set loopEnd(value: string | number);
354
+ /**
355
+ * Normalised loop position [0, 1]. Always 0 when loop=false.
356
+ */
357
+ get progress(): number;
358
+ /**
359
+ * Schedule a callback to fire on every `interval` while the sequencer plays.
360
+ * Returns a cancel function.
361
+ *
362
+ * @param callback Called with the exact AudioContext time of each firing.
363
+ * @param interval Musical interval: "4n", "8n", "1m", ticks, etc.
364
+ * @param startAt First firing position (default 0 = beginning).
365
+ */
366
+ scheduleRepeat(callback: (time: number) => void, interval: string | number, startAt?: string | number): () => void;
367
+ /**
368
+ * Listen to a sequencer event.
369
+ *
370
+ * | Event | Args |
371
+ * |----------------|---------------------------------------------------|
372
+ * | "statechange" | (state: "playing" \| "paused" \| "stopped") |
373
+ * | "start" | |
374
+ * | "stop" | |
375
+ * | "pause" | |
376
+ * | "end" | |
377
+ * | "loop" | |
378
+ * | "beat" | (beat: number, time: number) |
379
+ * | "bar" | (bar: number, time: number) |
380
+ * | "noteOn" | (event: NoteEvent) |
381
+ * | "noteOff" | (event: NoteEvent) |
382
+ */
383
+ on(event: string, callback: (...args: any[]) => void): this;
384
+ off(event: string, callback: (...args: any[]) => void): this;
385
+ private _startLoop;
386
+ private _stopLoop;
387
+ private _flush;
388
+ private _scheduleWindow;
389
+ private _emitBeatsInWindow;
390
+ private _emit;
391
+ /** Emit both the specific state event ("start"/"pause"/"stop") and the unified "statechange" event. */
392
+ private _emitStateChange;
393
+ /** Recompute _totalTicks from all track notes (at + duration). */
394
+ private _recomputeTotalTicks;
395
+ /** Format a raw tick count as "bar:beat:tick" (all 1-indexed). */
396
+ private _tickToPosition;
397
+ /**
398
+ * Reset all repeat events so their next firing is the first occurrence
399
+ * at or after `fromTick`.
400
+ */
401
+ private _resetRepeatEvents;
402
+ }
403
+
221
404
  declare function getElectricPianoNames(): string[];
222
405
  type ElectricPianoOptions = Partial<{
223
406
  instrument: string;
@@ -241,7 +424,7 @@ declare class ElectricPiano {
241
424
  });
242
425
  get output(): OutputChannel;
243
426
  get loadProgress(): LoadProgress;
244
- start(sample: NoteEvent | string | number): StopFn;
427
+ start(sample: NoteEvent$1 | string | number): StopFn;
245
428
  stop(target?: StopTarget): void;
246
429
  disconnect(): void;
247
430
  }
@@ -270,7 +453,7 @@ declare class Versilian {
270
453
  constructor(context: BaseAudioContext, options?: VersilianOptions);
271
454
  get output(): OutputChannel;
272
455
  get loadProgress(): LoadProgress;
273
- start(sample: NoteEvent | string | number): StopFn;
456
+ start(sample: NoteEvent$1 | string | number): StopFn;
274
457
  stop(target?: StopTarget): void;
275
458
  disconnect(): void;
276
459
  }
@@ -301,7 +484,7 @@ declare class Mellotron {
301
484
  constructor(context: BaseAudioContext, options?: MellotronOptions);
302
485
  get output(): OutputChannel;
303
486
  get loadProgress(): LoadProgress;
304
- start(sample: NoteEvent | string | number): StopFn;
487
+ start(sample: NoteEvent$1 | string | number): StopFn;
305
488
  stop(target?: StopTarget): void;
306
489
  disconnect(): void;
307
490
  }
@@ -359,7 +542,7 @@ declare class Sampler {
359
542
  constructor(context: AudioContext, options?: Partial<SamplerConfig>);
360
543
  loaded(): Promise<this>;
361
544
  get output(): OutputChannel;
362
- start(sample: NoteEvent | string | number): StopFn;
545
+ start(sample: NoteEvent$1 | string | number): StopFn;
363
546
  stop(sample?: StopTarget | string | number): void;
364
547
  disconnect(): void;
365
548
  }
@@ -399,7 +582,7 @@ declare class Smolken {
399
582
  constructor(context: BaseAudioContext, options?: SmolkenOptions);
400
583
  get output(): OutputChannel;
401
584
  get loadProgress(): LoadProgress;
402
- start(sample: NoteEvent | string | number): StopFn;
585
+ start(sample: NoteEvent$1 | string | number): StopFn;
403
586
  stop(target?: StopTarget): void;
404
587
  disconnect(): void;
405
588
  }
@@ -433,7 +616,7 @@ declare class Soundfont {
433
616
  get output(): OutputChannel;
434
617
  loaded(): Promise<this>;
435
618
  disconnect(): void;
436
- start(sample: NoteEvent | string | number): StopFn;
619
+ start(sample: NoteEvent$1 | string | number): StopFn;
437
620
  stop(sample?: StopTarget | string | number): void;
438
621
  }
439
622
  /**
@@ -492,7 +675,7 @@ declare class Soundfont2Sampler {
492
675
  get instrumentNames(): string[];
493
676
  get output(): OutputChannel;
494
677
  loadInstrument(instrumentName: string): Promise<void> | undefined;
495
- start(sample: NoteEvent | string | number): StopFn;
678
+ start(sample: NoteEvent$1 | string | number): StopFn;
496
679
  stop(sample?: StopTarget | string | number): void;
497
680
  disconnect(): void;
498
681
  }
@@ -532,7 +715,7 @@ declare class SplendidGrandPiano {
532
715
  get loadProgress(): LoadProgress;
533
716
  /** @deprecated Use `load` instead. */
534
717
  loaded(): Promise<this>;
535
- start(event: NoteEvent): StopFn;
718
+ start(event: NoteEvent$1): StopFn;
536
719
  stop(target?: StopTarget): void;
537
720
  disconnect(): void;
538
721
  }
@@ -561,4 +744,4 @@ declare const LAYERS: ({
561
744
  cutoff?: undefined;
562
745
  })[];
563
746
 
564
- export { CacheStorage, DrumMachine, type DrumMachineOptions, ElectricPiano, type ElectricPianoOptions, HttpStorage, LAYERS, Mallet, Mellotron, type MellotronConfig, type MellotronOptions, NAME_TO_PATH, Reverb, Sampler, type SamplerConfig, Smolken, type SmolkenConfig, type SmolkenOptions, Soundfont, type Soundfont2Options, Soundfont2Sampler, type SoundfontOptions, SplendidGrandPiano, type SplendidGrandPianoConfig, type Storage, type StorageResponse, Versilian, type VersilianConfig, type VersilianOptions, drumMachineToSmplrJson, getDrumMachineNames, getElectricPianoNames, getMalletNames, getMellotronNames, getSmolkenNames, getSoundfontKits, getSoundfontNames, getVersilianInstruments, mellotronToSmplrJson, pianoToSmplrJson, samplerToSmplrJson, sf2InstrumentToSmplrJson, soundfontToSmplrJson, spreadKeyRanges };
747
+ export { CacheStorage, DrumMachine, type DrumMachineOptions, ElectricPiano, type ElectricPianoOptions, HttpStorage, LAYERS, Mallet, Mellotron, type MellotronConfig, type MellotronOptions, NAME_TO_PATH, type NoteEvent, Reverb, Sampler, type SamplerConfig, Sequencer, type SequencerInstrument, type SequencerNote, type SequencerOptions, Smolken, type SmolkenConfig, type SmolkenOptions, Soundfont, type Soundfont2Options, Soundfont2Sampler, type SoundfontOptions, SplendidGrandPiano, type SplendidGrandPianoConfig, type Storage, type StorageResponse, Versilian, type VersilianConfig, type VersilianOptions, drumMachineToSmplrJson, getDrumMachineNames, getElectricPianoNames, getMalletNames, getMellotronNames, getSmolkenNames, getSoundfontKits, getSoundfontNames, getVersilianInstruments, mellotronToSmplrJson, pianoToSmplrJson, samplerToSmplrJson, sf2InstrumentToSmplrJson, soundfontToSmplrJson, spreadKeyRanges };