summaryrefslogtreecommitdiff
path: root/src/lib/sampler.js
blob: 0a00792a09e781816733a2f24b2d55c4984b1ae4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import * as Tone from "tone";
import { choice, randrange } from "./util";
import output from "./output";

const PLAYER_COUNT = 4;

export default class Sampler {
  constructor({ samples, tonal }) {
    this.tonal = tonal;
    this.samples = samples.map(({ ...sample }) => {
      sample.players = [];
      sample.index = -1;
      for (let i = 0; i < PLAYER_COUNT; i++) {
        let fn = sample.fn;
        if (window.location.href.match(/asdf.us/)) {
          fn = "//asdf.us/kalimba/" + fn;
        }
        let player = new Tone.Player({
          url: fn,
          retrigger: true,
          playbackRate: 1,
        });
        player.connect(output);
        sample.players.push(player);
      }
      return sample;
    });
  }

  play(time, options, velocity) {
    const sound = options.index
      ? this.samples[options.index]
      : choice(this.samples);

    sound.index = (sound.index + 1) % PLAYER_COUNT;

    const player = sound.players[sound.index];

    if (this.tonal) {
      player.playbackRate =
        (options.frequency * choice([0.5, 1]) + randrange(0, 10)) / sound.root;
    }

    if (velocity) {
      player.volume.value = (1 - velocity) * -18;
      console.log(player.volume.value);
    }

    player.start(time || 0);
  }
}