1import { Pattern, getPlayableNoteValue, noteToMidi } from '@strudel/core';
2import { getAudioContext, registerSound } from '@strudel/webaudio';
3import { loadSoundfont as _loadSoundfont, startPresetNote } from 'sfumato';
4
5Pattern.prototype.soundfont = function (sf, n = 0) {
6  return this.onTrigger((h, ct, cps, targetTime) => {
7    const ctx = getAudioContext();
8    const note = getPlayableNoteValue(h);
9    const preset = sf.presets[n % sf.presets.length];
10    const deadline = targetTime;
11    const args = [ctx, preset, noteToMidi(note), deadline];
12    const stop = startPresetNote(...args);
13    stop(deadline + h.duration);
14  });
15};
16
17const soundfontCache = new Map();
18export function loadSoundfont(url) {
19  if (soundfontCache.get(url)) {
20    return soundfontCache.get(url);
21  }
22  const sf = _loadSoundfont(url);
23  soundfontCache.set(url, sf);
24  /*sf.then((font) => {
25    font.presets.forEach((preset) => {
26      console.log('preset', preset.header.name);
27      registerSound(
28        preset.header.name.replaceAll(' ', '_'),
29        (time, value, onended) => {
30          const ctx = getAudioContext();
31          let { note } = value; // freq ?
32
33          const p = font.presets.find((p) => p.header.name === preset.header.name);
34
35          if (!p) {
36            throw new Error('preset not found');
37          }
38          const deadline = time; // - ctx.currentTime;
39          const args = [ctx, p, noteToMidi(note), deadline];
40          const stop = startPresetNote(...args);
41          return { node: undefined, stop };
42        },
43        { type: 'soundfont' },
44      );
45    });
46    //console.log('f', f);
47  });*/
48  return sf;
49}