jevstrudel.git / packages / xen / tune.mjs
1/*
2tune.mjs - <short description TODO>
3Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/xen/tune.mjs>
4This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <https://www.gnu.org/licenses/>.
5*/
6
7import Tune from './tunejs.js';
8import { register } from '@strudel/core';
9
10/**
11 * Assumes pattern contains numerical scale degrees on the `i` control (see examples below). Accepts a scale name or list of frequencies (see all available names at the link on the reference). Returns a new pattern with all values mapped to a frequency ratio. Similar to `xen`.
12 * @name tune
13 * @returns Pattern
14 * @memberof Pattern
15 * @param {(string | number[] )} scale
16 * @example
17 * i("0 1 2 3 4 5").tune("hexany15").mul("220").freq()
18 * @example
19 * // You can set your root to be a
20 * // particular note with getFreq:
21 * i("4 8 9 10 - - 5 7 9 11 - -").tune("tranh3")
22 *   .mul(getFreq('c3'))
23 *   .freq().clip(.5).room(1)
24 * @example
25 * // You can also give tune a list of
26 * // frequencies to use as the scale:
27 * i("0 1 2 3 4").tune([
28 *   261.6255653006,
29 *   302.72962012827,
30 *   350.29154279212,
31 *   405.32593044476,
32 *   469.00678383895,
33 *   523.2511306012
34 * ]).mul(220).freq();
35 *
36 * @tags tonal
37 */
38
39// Tune.scale seems to be in ratio format
40export const tune = register('tune', (scale, pat) => {
41  const tune = new Tune();
42  if (!tune.isValidScale(scale)) {
43    throw new Error('not a valid tune.js scale name: "' + scale + '". See http://abbernie.github.io/tune/scales.html');
44  }
45  tune.loadScale(scale);
46  // if the tonic is a frequency, why are we putting in "1"
47  tune.tonicize(1);
48  return pat.withHap((hap) => {
49    if (typeof hap.value !== 'object') {
50      throw new Error(`Expected hap to have control 'i' set, but received ${hap.value.i}, try wrapping input in i()`);
51    }
52    // const { i, ...otherValues } = hap.value;
53    // hap.value = { ...otherValues, freq: tune.note(i)}
54    // return hap
55    return hap.withValue(() => tune.note(hap.value.i));
56  });
57});