Compare commits

..

88 Commits

Author SHA1 Message Date
Jade (Rose) Rowland b8e1b8d7ac Merge branch 'main' into supradough 2025-08-31 22:42:07 -04:00
yaxu dc6b766ab7 Update README.md 2025-08-30 12:47:06 +02:00
yaxu 9eb3c9410d Add verify link to mastodon a/c 2025-08-30 12:46:00 +02:00
Switch Angel AKA Jade Rose b54139376e Merge pull request 'Bug Fix: Duck on Mobile / Safari' (#1503) from glossing/strudel:glossing/ducks-on-mobile into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/1503
2025-08-25 02:31:21 +02:00
Aria d64a0ef0eb Lint requires no empty blocks: pass comment 2025-08-25 02:31:21 +02:00
Aria 659071a4ee Ensure zeroGain is cleaned up after use; move start/stop to after callback assigned for safety 2025-08-25 02:31:21 +02:00
Aria 64f7bc4442 Working version of duck on iOS safari 2025-08-25 02:31:21 +02:00
Alex McLean 8c97f2e2d0 Merge pull request 'fix benchmarks' (#1517) from fix-bench into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/1517
2025-08-23 18:39:52 +02:00
alex b8c98736c5 fix benchmarks 2025-08-23 17:29:15 +01:00
froos 0693a32736 Merge pull request 'add --json flag to @strudel/sampler to generate a strudel.json' (#1513) from strudeljson-generate into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/1513
2025-08-21 20:57:31 +02:00
Felix Roos 42a903ecc0 add --yes flag to readme, making sure first run works 2025-08-21 20:36:42 +02:00
Felix Roos da283eb55a doc: generate strudel.json 2025-08-21 20:36:17 +02:00
Felix Roos b12707316a bump @strudel/sampler to 0.2.1 2025-08-21 20:30:32 +02:00
Felix Roos 66aa3ac1da add --json flag to strudel sampler 2025-08-21 20:30:02 +02:00
froos d81b1ab65c Merge pull request 'remove hs2js postinstall' (#1510) from remove-postinstall into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/1510
2025-08-21 10:04:28 +02:00
Felix Roos 8465517c76 remove hs2js postinstall 2025-08-21 10:00:41 +02:00
Felix Roos 215ab87809 fix: prettier 2025-08-21 09:41:21 +02:00
froos e5fe998327 Merge pull request 'Docs: Small additions to Learn Docs and fixed refrences to function Documentation' (#1502) from fyynn/strudel:main into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/1502
2025-08-20 15:15:31 +02:00
froos 6f75a0a62b Merge pull request 'fix: repl autocomplete not rendering correctly' (#1480) from robase/strudel:fix-repl-autocomplete-styles into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/1480
2025-08-20 12:31:36 +02:00
froos 0464845262 Merge pull request 'BUG FIX: make 'midin' initialization work with multiple controllers' (#1469) from cbabraham/strudel:fix/midi-init-bug into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/1469
2025-08-20 12:10:00 +02:00
fyynn d6ee10e05c fixed new scrub refrence 2025-08-19 00:44:46 +02:00
fyynn 36441e7b73 Fixing hush refrence to code documentation
Signed-off-by: fyynn <fyynn@noreply.codeberg.org>
2025-08-19 00:25:31 +02:00
fyynn 189daa3942 Added Refrence to arp() arpWidth() to Docs
Signed-off-by: fyynn <fyynn@noreply.codeberg.org>
2025-08-19 00:21:32 +02:00
fyynn d009b9592e Added Refrence to arp() arpWidth() and hush to Docs
Signed-off-by: fyynn <fyynn@noreply.codeberg.org>
2025-08-19 00:09:41 +02:00
fyynn f7f1bd63e8 Adding the Duck/Sidechain effect to Learn Docs (learn/effects.mdx)
Added the duck Effect to the section global effects.

Signed-off-by: fyynn <fyynn@noreply.codeberg.org>
2025-08-18 23:49:43 +02:00
fyynn 7d24e45692 Added scrub() to Learn Docs
Signed-off-by: fyynn <fyynn@noreply.codeberg.org>
2025-08-18 23:36:39 +02:00
robase 612efad3eb clean up comments 2025-08-07 09:25:01 +02:00
robase e7839a09a1 fix: tooltip should respect themes 2025-08-07 09:25:01 +02:00
robase 3292f88810 fix: repl autocomplete not rendering correctly 2025-08-07 09:25:01 +02:00
Chandler Abraham 2eda047108 Merge branch 'main' of https://codeberg.org/uzu/strudel into fix/midi-init-bug 2025-07-22 21:52:03 -07:00
Chandler Abraham c8cf1dc712 fix(midi): ensure midin initializes device state correctly
The midin function only initialized the refs object for a device on the initial MIDI setup. This caused an error if a second MIDI device was connected in the same session, as its refs object would not exist, leading to a 'cannot read properties of undefined' error when accessed.

This commit fixes the issue by ensuring that the refs object for a given MIDI input is initialized every time  is called, not just on the first call.
2025-07-22 21:49:40 -07:00
daslyfe a26559fd3d Merge branch 'main' into supradough 2025-07-22 06:35:59 +02:00
Felix Roos 5632d83afb fix: supradough onTrigger after breaking change 2025-07-16 02:21:39 +02:00
Felix Roos a32473d570 Merge remote-tracking branch 'origin/main' into supradough 2025-07-15 22:26:46 +02:00
froos 8051e56d13 Merge branch 'main' into supradough 2025-06-14 00:35:52 +02:00
Felix Roos 239987af0b snapshot 2025-06-12 10:23:06 +02:00
Felix Roos 8363ba5a41 format 2025-06-12 10:22:35 +02:00
Felix Roos 30f7127a92 Merge remote-tracking branch 'origin/main' into supradough 2025-06-12 10:22:08 +02:00
Felix Roos 14193abe03 improve export: add stereo + measure performance + add bigger pattern for testing 2025-06-12 02:26:50 +02:00
Felix Roos 3caf08e199 up latency 2025-06-12 02:26:08 +02:00
Felix Roos 5cbd38a3e8 improve filter performance making it accept hz directly 2025-06-12 02:25:46 +02:00
Felix Roos bbd7ed0f27 lazy sample loading 2025-06-12 02:25:04 +02:00
Jade (Rose) Rowland 43504d16b6 add chorus 2025-06-10 16:03:42 +02:00
Jade (Rose) Rowland 7e8206dcbc pitched delay 2025-06-10 12:31:21 +02:00
Felix Roos 3963b807eb fix: calling doughsamples multiple times 2025-06-09 22:32:41 +02:00
Felix Roos e99adffc56 vibrato 2025-06-09 22:29:35 +02:00
Felix Roos c9f494d865 fix: node export 2025-06-09 22:10:09 +02:00
Felix Roos e8254735bb apply speed to synths and samples + add normalize flag (for fit) 2025-06-09 19:35:50 +02:00
Jade (Rose) Rowland 3d30007756 supersaw 2025-06-09 15:55:44 +02:00
Jade (Rose) Rowland aeaed50446 gaincurve 2025-06-09 15:18:47 +02:00
Felix Roos 3ac0fdf619 rudimentary sample map loading (doughsamples) 2025-06-09 11:07:57 +02:00
Felix Roos d1b6b6be85 fix: hpf 2025-06-09 09:54:24 +02:00
Felix Roos 1081fc69e9 refactor: stereo sample support + channelwise fx 2025-06-09 09:52:29 +02:00
Felix Roos 73ef43dd2c move things around in init
+ shorten things
2025-06-08 22:56:55 +02:00
Jade (Rose) Rowland 181e51ef0e adjustable envelope curves 2025-06-08 20:26:20 +02:00
Jade (Rose) Rowland 1167fdb910 Merge branch 'supradough' of https://github.com/tidalcycles/strudel into supradough 2025-06-08 19:25:47 +02:00
Jade (Rose) Rowland ec9109dd89 exponential lerp 2025-06-08 19:24:55 +02:00
Felix Roos 55aef18851 buffers can now be repitched (still with aliasing) 2025-06-08 14:43:23 +02:00
Felix Roos 356d4360ec fix: scheduling + sample playback 2025-06-08 09:05:14 +02:00
Felix Roos 0f2aa9569b half working samples 2025-06-08 02:04:49 +02:00
Felix Roos ac7ee376e5 pitch envelope 2025-06-08 00:43:58 +02:00
Felix Roos ab052ce1ac fix: polyblepped sawtooth + fm = death 2025-06-07 23:15:09 +02:00
Felix Roos 5988e3d3b4 fix: hot reloading for dough.mjs (see comment) 2025-06-07 22:42:48 +02:00
Felix Roos 2f2bf5bf29 fix: note2midi for notes without octave 2025-06-07 22:36:54 +02:00
Felix Roos b000f2297d fm 2025-06-07 20:31:47 +02:00
Felix Roos 77463a199a add square alias for pulse 2025-06-07 13:26:43 +02:00
Felix Roos e54449f5f7 white brown pink noise + crackle alias for dust 2025-06-07 13:24:06 +02:00
Felix Roos d743570546 set delay time and feedback from voice 2025-06-07 13:12:35 +02:00
Felix Roos 1dac69635d feedback delay (still hard coded feedback / time values) 2025-06-07 10:40:34 +02:00
Felix Roos 49f38aeddb remove log 2025-06-06 16:26:17 +02:00
Felix Roos 43c05cb504 move supradough to separate package 2025-06-06 16:17:05 +02:00
Felix Roos ccc90d547c ignore dough-export to fix checks 2025-06-06 15:47:19 +02:00
Felix Roos 998a010247 better filter envelopes 2025-06-06 11:21:01 +02:00
Felix Roos e4cd5dc552 rough filter envelope implementation 2025-06-06 10:55:38 +02:00
Felix Roos 6cf0b6f651 hpf + bpf 2025-06-06 10:12:49 +02:00
Felix Roos 794bf86904 distort 2025-06-06 09:56:41 +02:00
Felix Roos 9ed690ce45 pulse osc + velocity 2025-06-06 09:37:40 +02:00
Felix Roos 623bf93368 panning 2025-06-06 08:50:02 +02:00
Felix Roos 0cc18a6468 crush (might be wrong) 2025-06-06 08:27:47 +02:00
Felix Roos 87598e10d1 coarse 2025-06-06 08:17:20 +02:00
Felix Roos ccec7e725a poc: render pattern audio with node script 2025-06-05 11:04:55 +02:00
Felix Roos f0e6c5483c handle invalid spawns + remove logs 2025-06-05 10:30:53 +02:00
Felix Roos 2cbd35f6d2 refactor: make webaudio glue as minimal as possible 2025-06-05 10:26:14 +02:00
Felix Roos 930dabe4d6 dough as a singleton worklet with voice allocation 2025-06-05 09:54:44 +02:00
Jade (Rose) Rowland ff4b7ca171 fix volume 2025-06-04 01:08:36 +01:00
Jade (Rose) Rowland 5129fa6677 fix click 2025-06-04 00:48:32 +01:00
Felix Roos 5336569c25 proper lpf mapping + remove redundant worklet params, 2025-06-01 21:20:28 +02:00
Felix Roos 483843bd0a begin supradough 2025-06-01 18:06:36 +02:00
31 changed files with 1788 additions and 143 deletions
+2 -2
View File
@@ -3,8 +3,6 @@
Live coding patterns on the web
https://strudel.cc/
Development is moving to https://codeberg.org/uzu/strudel
- Try it here: <https://strudel.cc>
- Docs: <https://strudel.cc/learn>
- Technical Blog Post: <https://loophole-letters.vercel.app/strudel>
@@ -47,3 +45,5 @@ There is a #strudel channel on the TidalCycles discord: <https://discord.com/inv
You can also ask questions and find related discussions on the tidal club forum: <https://club.tidalcycles.org/>
The discord and forum is shared with the haskell (tidal) and python (vortex) siblings of this project.
We also have a mastodon account: <a rel="me" href="https://social.toplap.org/@strudel">social.toplap.org/@strudel</a>
+1
View File
@@ -42,6 +42,7 @@ export default [
'**/hydra.mjs',
'**/jsdoc-synonyms.js',
'packages/hs2js/src/hs2js.mjs',
'packages/supradough/dough-export.mjs',
'**/samples',
],
},
+69 -52
View File
@@ -1,68 +1,91 @@
import jsdoc from '../../doc.json';
// import { javascriptLanguage } from '@codemirror/lang-javascript';
import { autocompletion } from '@codemirror/autocomplete';
import { h } from './html';
function plaintext(str) {
const escapeHtml = (str) => {
const div = document.createElement('div');
div.innerText = str;
return div.innerHTML;
}
};
const getDocLabel = (doc) => doc.name || doc.longname;
const getInnerText = (html) => {
var div = document.createElement('div');
const stripHtml = (html) => {
const div = document.createElement('div');
div.innerHTML = html;
return div.textContent || div.innerText || '';
};
export function Autocomplete({ doc, label }) {
return h`<div class="prose dark:prose-invert max-h-[400px] overflow-auto p-2">
<h1 class="pt-0 mt-0">${label || getDocLabel(doc)}</h1>
${doc.description}
<ul>
${doc.params?.map(
({ name, type, description }) =>
`<li>${name} : ${type.names?.join(' | ')} ${description ? ` - ${getInnerText(description)}` : ''}</li>`,
)}
</ul>
<div>
${doc.examples?.map((example) => `<div><pre>${plaintext(example)}</pre></div>`)}
</div>
</div>`[0];
/*
<pre
className="cursor-pointer"
onMouseDown={(e) => {
console.log('ola!');
navigator.clipboard.writeText(example);
e.stopPropagation();
}}
>
{example}
</pre>
*/
}
const getDocLabel = (doc) => doc.name || doc.longname;
const buildParamsList = (params) =>
params?.length
? `
<div class="autocomplete-info-params-section">
<h4 class="autocomplete-info-section-title">Parameters</h4>
<ul class="autocomplete-info-params-list">
${params
.map(
({ name, type, description }) => `
<li class="autocomplete-info-param-item">
<span class="autocomplete-info-param-name">${name}</span>
<span class="autocomplete-info-param-type">${type.names?.join(' | ')}</span>
${description ? `<div class="autocomplete-info-param-desc">${stripHtml(description)}</div>` : ''}
</li>
`,
)
.join('')}
</ul>
</div>
`
: '';
const buildExamples = (examples) =>
examples?.length
? `
<div class="autocomplete-info-examples-section">
<h4 class="autocomplete-info-section-title">Examples</h4>
${examples
.map(
(example) => `
<pre class="autocomplete-info-example-code">${escapeHtml(example)}</pre>
`,
)
.join('')}
</div>
`
: '';
export const Autocomplete = ({ doc, label }) =>
h`
<div class="autocomplete-info-tooltip">
<h3 class="autocomplete-info-function-name">${label || getDocLabel(doc)}</h3>
${doc.description ? `<p class="autocomplete-info-function-description">${doc.description}</p>` : ''}
${buildParamsList(doc.params)}
${buildExamples(doc.examples)}
</div>
`[0];
const isValidDoc = (doc) => {
const label = getDocLabel(doc);
return label && !label.startsWith('_') && !['package'].includes(doc.kind);
};
const hasExcludedTags = (doc) =>
['superdirtOnly', 'noAutocomplete'].some((tag) => doc.tags?.find((t) => t.originalTitle === tag));
const jsdocCompletions = jsdoc.docs
.filter(
(doc) =>
getDocLabel(doc) &&
!getDocLabel(doc).startsWith('_') &&
!['package'].includes(doc.kind) &&
!['superdirtOnly', 'noAutocomplete'].some((tag) => doc.tags?.find((t) => t.originalTitle === tag)),
)
.filter((doc) => isValidDoc(doc) && !hasExcludedTags(doc))
// https://codemirror.net/docs/ref/#autocomplete.Completion
.map((doc) /*: Completion */ => ({
.map((doc) => ({
label: getDocLabel(doc),
// detail: 'xxx', // An optional short piece of information to show (with a different style) after the label.
info: () => Autocomplete({ doc }),
type: 'function', // https://codemirror.net/docs/ref/#autocomplete.Completion.type
}));
export const strudelAutocomplete = (context /* : CompletionContext */) => {
let word = context.matchBefore(/\w*/);
if (word.from == word.to && !context.explicit) return null;
export const strudelAutocomplete = (context) => {
const word = context.matchBefore(/\w*/);
if (word.from === word.to && !context.explicit) return null;
return {
from: word.from,
options: jsdocCompletions,
@@ -74,11 +97,5 @@ export const strudelAutocomplete = (context /* : CompletionContext */) => {
};
};
export function isAutoCompletionEnabled(on) {
return on
? [
autocompletion({ override: [strudelAutocomplete] }),
//javascriptLanguage.data.of({ autocomplete: strudelAutocomplete }),
]
: []; // autocompletion({ override: [] })
}
export const isAutoCompletionEnabled = (enabled) =>
enabled ? [autocompletion({ override: [strudelAutocomplete] })] : [];
+6 -6
View File
@@ -1,11 +1,11 @@
import { describe, bench } from 'vitest';
import { calculateTactus, sequence, stack } from '../index.mjs';
import { calculateSteps, sequence, stack } from '../index.mjs';
const pat64 = sequence(...Array(64).keys());
describe('steps', () => {
calculateTactus(true);
calculateSteps(true);
bench(
'+tactus',
() => {
@@ -14,7 +14,7 @@ describe('steps', () => {
{ time: 1000 },
);
calculateTactus(false);
calculateSteps(false);
bench(
'-tactus',
() => {
@@ -25,7 +25,7 @@ describe('steps', () => {
});
describe('stack', () => {
calculateTactus(true);
calculateSteps(true);
bench(
'+tactus',
() => {
@@ -34,7 +34,7 @@ describe('stack', () => {
{ time: 1000 },
);
calculateTactus(false);
calculateSteps(false);
bench(
'-tactus',
() => {
@@ -43,4 +43,4 @@ describe('stack', () => {
{ time: 1000 },
);
});
calculateTactus(true);
calculateSteps(true);
+27 -3
View File
@@ -309,6 +309,17 @@ export const { fmvelocity } = registerControl('fmvelocity');
*/
export const { bank } = registerControl('bank');
/**
* mix control for the chorus effect
*
* @name chorus
* @param {string | Pattern} chorus mix amount between 0 and 1
* @example
* note("d d a# a").s("sawtooth").chorus(.5)
*
*/
export const { chorus } = registerControl('chorus');
// analyser node send amount 0 - 1 (used by scope)
export const { analyze } = registerControl('analyze');
// fftSize of analyser
@@ -1097,14 +1108,27 @@ export const { delay } = registerControl(['delay', 'delaytime', 'delayfeedback']
*
*/
export const { delayfeedback, delayfb, dfb } = registerControl('delayfeedback', 'delayfb', 'dfb');
/**
* Sets the level of the signal that is fed back into the delay.
* Caution: Values >= 1 will result in a signal that gets louder and louder! Don't do it
*
* @name delayfeedback
* @param {number | Pattern} feedback between 0 and 1
* @synonyms delayfb, dfb
* @example
* s("bd").delay(.25).delayfeedback("<.25 .5 .75 1>")
*
*/
export const { delayspeed } = registerControl('delayspeed');
/**
* Sets the time of the delay effect.
*
* @name delaytime
* @param {number | Pattern} seconds between 0 and Infinity
* @name delayspeed
* @param {number | Pattern} delayspeed controls the pitch of the delay feedback
* @synonyms delayt, dt
* @example
* s("bd bd").delay(.25).delaytime("<.125 .25 .5 1>")
* note("d d a# a".fast(2)).s("sawtooth").delay(.8).delaytime(1/2).delayspeed("<2 .5 -1 -2>")
*
*/
export const { delaytime, delayt, dt } = registerControl('delaytime', 'delayt', 'dt');
+3
View File
@@ -493,6 +493,9 @@ export async function midin(input) {
otherInputs?.length ? `Also available: ${getMidiDeviceNamesString(otherInputs)}` : ''
}`,
);
}
// ensure refs for this input are initialized
if (!refs[input]) {
refs[input] = {};
}
const cc = (cc) => ref(() => refs[input][cc] || 0);
+4 -4
View File
@@ -1,10 +1,10 @@
import { describe, bench } from 'vitest';
import { calculateTactus } from '../../core/index.mjs';
import { calculateSteps } from '../../core/index.mjs';
import { mini } from '../index.mjs';
describe('mini', () => {
calculateTactus(true);
calculateSteps(true);
bench(
'+tactus',
() => {
@@ -13,7 +13,7 @@ describe('mini', () => {
{ time: 1000 },
);
calculateTactus(false);
calculateSteps(false);
bench(
'-tactus',
() => {
@@ -21,5 +21,5 @@ describe('mini', () => {
},
{ time: 1000 },
);
calculateTactus(true);
calculateSteps(true);
});
+10
View File
@@ -20,3 +20,13 @@ samples('http://localhost:5432')
LOG=1 npx @strudel/sampler # adds logging
PORT=5555 npx @strudel/sampler # changes port
```
## static json
when running with `--json`, you will simply get the json logged back:
```sh
npx --yes @strudel/sampler --json > strudel.json
```
this is useful if you want to create a sample pack from the current folder.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/sampler",
"version": "0.2.0",
"version": "0.2.2",
"description": "",
"keywords": [
"tidalcycles",
+18 -8
View File
@@ -10,14 +10,6 @@ import os from 'os';
// eslint-disable-next-line
const LOG = !!process.env.LOG || false;
console.log(
cowsay.say({
text: 'welcome to @strudel/sampler',
e: 'oO',
T: 'U ',
}),
);
async function getFilesInDirectory(directory) {
let files = [];
const dirents = await readdir(directory, { withFileTypes: true });
@@ -60,8 +52,26 @@ async function getBanks(directory) {
return { banks, files };
}
const args = process.argv.slice(2);
// eslint-disable-next-line
const directory = process.cwd();
if (args.includes('--json')) {
const { banks, files } = await getBanks(directory);
const json = JSON.stringify(banks);
console.log(json);
process.exit(0);
}
console.log(
cowsay.say({
text: 'welcome to @strudel/sampler',
e: 'oO',
T: 'U ',
}),
);
const server = http.createServer(async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
const { banks, files } = await getBanks(directory);
+20 -2
View File
@@ -211,11 +211,29 @@ export function getVibratoOscillator(param, value, t) {
export function webAudioTimeout(audioContext, onComplete, startTime, stopTime) {
const constantNode = new ConstantSourceNode(audioContext);
constantNode.start(startTime);
constantNode.stop(stopTime);
// Certain browsers requires audio nodes to be connected in order for their onended events
// to fire, so we _mute it_ and then connect it to the destination
const zeroGain = gainNode(0);
zeroGain.connect(audioContext.destination);
constantNode.connect(zeroGain);
// Schedule the `onComplete` callback to occur at `stopTime`
constantNode.onended = () => {
// Ensure garbage collection
try {
zeroGain.disconnect();
} catch {
// pass
}
try {
constantNode.disconnect();
} catch {
// pass
}
onComplete();
};
constantNode.start(startTime);
constantNode.stop(stopTime);
return constantNode;
}
const mod = (freq, range = 1, type = 'sine') => {
+48 -43
View File
@@ -196,6 +196,52 @@ function getSamplesPrefixHandler(url) {
return;
}
export async function fetchSampleMap(url) {
// check if custom prefix handler
const handler = getSamplesPrefixHandler(url);
if (handler) {
return handler(url);
}
url = resolveSpecialPaths(url);
if (url.startsWith('github:')) {
url = githubPath(url, 'strudel.json');
}
if (url.startsWith('local:')) {
url = `http://localhost:5432`;
}
if (url.startsWith('shabda:')) {
let [_, path] = url.split('shabda:');
url = `https://shabda.ndre.gr/${path}.json?strudel=1`;
}
if (url.startsWith('shabda/speech')) {
let [_, path] = url.split('shabda/speech');
path = path.startsWith('/') ? path.substring(1) : path;
let [params, words] = path.split(':');
let gender = 'f';
let language = 'en-GB';
if (params) {
[language, gender] = params.split('/');
}
url = `https://shabda.ndre.gr/speech/${words}.json?gender=${gender}&language=${language}&strudel=1'`;
}
if (typeof fetch !== 'function') {
// not a browser
return;
}
const base = url.split('/').slice(0, -1).join('/');
if (typeof fetch === 'undefined') {
// skip fetch when in node / testing
return;
}
const json = await fetch(url)
.then((res) => res.json())
.catch((error) => {
console.error(error);
throw new Error(`error loading "${url}"`);
});
return [json, json._base || base];
}
/**
* Loads a collection of samples to use with `s`
* @example
@@ -217,49 +263,8 @@ function getSamplesPrefixHandler(url) {
export const samples = async (sampleMap, baseUrl = sampleMap._base || '', options = {}) => {
if (typeof sampleMap === 'string') {
// check if custom prefix handler
const handler = getSamplesPrefixHandler(sampleMap);
if (handler) {
return handler(sampleMap);
}
sampleMap = resolveSpecialPaths(sampleMap);
if (sampleMap.startsWith('github:')) {
sampleMap = githubPath(sampleMap, 'strudel.json');
}
if (sampleMap.startsWith('local:')) {
sampleMap = `http://localhost:5432`;
}
if (sampleMap.startsWith('shabda:')) {
let [_, path] = sampleMap.split('shabda:');
sampleMap = `https://shabda.ndre.gr/${path}.json?strudel=1`;
}
if (sampleMap.startsWith('shabda/speech')) {
let [_, path] = sampleMap.split('shabda/speech');
path = path.startsWith('/') ? path.substring(1) : path;
let [params, words] = path.split(':');
let gender = 'f';
let language = 'en-GB';
if (params) {
[language, gender] = params.split('/');
}
sampleMap = `https://shabda.ndre.gr/speech/${words}.json?gender=${gender}&language=${language}&strudel=1'`;
}
if (typeof fetch !== 'function') {
// not a browser
return;
}
const base = sampleMap.split('/').slice(0, -1).join('/');
if (typeof fetch === 'undefined') {
// skip fetch when in node / testing
return;
}
return fetch(sampleMap)
.then((res) => res.json())
.then((json) => samples(json, baseUrl || json._base || base, options))
.catch((error) => {
console.error(error);
throw new Error(`error loading "${sampleMap}"`);
});
const [json, base] = await fetchSampleMap(sampleMap);
return samples(json, baseUrl || base, options);
}
const { prebake, tag } = options;
processSampleMap(
+8 -2
View File
@@ -196,7 +196,7 @@ export const resetLoadedSounds = () => soundMap.set({});
let audioContext;
export const setDefaultAudioContext = () => {
audioContext = new AudioContext();
audioContext = new AudioContext({ latencyHint: 'playback' });
return audioContext;
};
@@ -212,11 +212,17 @@ export function getAudioContextCurrentTime() {
return getAudioContext().currentTime;
}
let externalWorklets = [];
export function registerWorklet(url) {
externalWorklets.push(url);
}
let workletsLoading;
function loadWorklets() {
if (!workletsLoading) {
const audioCtx = getAudioContext();
workletsLoading = audioCtx.audioWorklet.addModule(workletsUrl);
const allWorkletURLs = externalWorklets.concat([workletsUrl]);
workletsLoading = Promise.all(allWorkletURLs.map((workletURL) => audioCtx.audioWorklet.addModule(workletURL)));
}
return workletsLoading;
+1
View File
@@ -0,0 +1 @@
pattern.wav
+3
View File
@@ -0,0 +1,3 @@
# supradough
platform agnostic synth and sampler intended for live coding. a reimplementation of superdough.
+123
View File
@@ -0,0 +1,123 @@
// this is a poc of how a pattern can be rendered as a wav file using node
// run via: node dough-export.mjs
import fs from 'node:fs';
import WavEncoder from 'wav-encoder';
import { evalScope } from '@strudel/core';
import { miniAllStrings } from '@strudel/mini';
import { Dough } from './dough.mjs';
await evalScope(
import('@strudel/core'),
import('@strudel/mini'),
import('@strudel/tonal'),
// import('@strudel/tonal'),
);
miniAllStrings(); // allows using single quotes for mini notation / skip transpilation
let sampleRate = 48000,
cps = 0.4;
/* await doughsamples('github:eddyflux/crate');
await doughsamples('github:eddyflux/wax'); */
let pat = note('c,eb,g,<bb c4 d4 eb4>')
.s('sine')
.press()
.add(note(24))
.fmi(3)
.fmh(5.01)
.dec(0.4)
.delay('.6:<.12 .22>:.8')
.jux(press)
.rarely(add(note('12')))
.lpf(400)
.lpq(0.2)
.lpd(0.4)
.lpenv(3)
.fmdecay(0.4)
.fmenv(1)
.postgain(0.6)
.stack(s('<pink white>*8').dec(0.07).rarely(ply('2')).delay(0.5).hpf(sine.range(200, 2000).slow(4)).hpq(0.2))
.stack(
s('[- white@3]*2')
.dec(0.4)
.hpf('<2000!3 <4000 8000>>*4')
.hpq(0.6)
.ply('<1 2>*4')
.postgain(0.5)
.delay(0.5)
.jux(rev)
.lpf(5000),
)
.stack(
note('<c2 - [- f1] ->*2')
.s('square')
.lpf(sine.range(100, 300).slow(4))
.lpe(1)
.segment(8)
.lpd(0.3)
.lpq(0.2)
.dec(0.2)
.speed('<1 2>')
.ply('<1 2>')
.postgain(1),
)
.stack(
chord('<Cm Cm7 Cm9 Cm11 Fm Fm7 Fm9 Fm11>')
.voicing()
.s('<sine>')
.clip(1)
.rel(0.4)
.vib('4:.2')
.gain(0.7)
.hpf(1200)
.fm(0.5)
.att(1)
.lpa(0.5)
.lpf(200)
.lpenv(4)
.chorus(0.8),
)
.slow(1 / cps);
let cycles = 30;
let seconds = cycles + 1; // 1s release tail
const haps = pat.queryArc(0, cycles);
const dough = new Dough(sampleRate);
console.log('spawn voices...');
haps.forEach((hap) => {
hap.value._begin = Number(hap.whole.begin);
hap.value._duration = hap.duration /* / cps */;
dough.scheduleSpawn(hap.value);
});
console.log(`render ${seconds}s long buffer, each dot is 1 second:`);
const buffers = [new Float32Array(seconds * sampleRate), new Float32Array(seconds * sampleRate)];
let t = performance.now();
while (dough.t <= buffers[0].length) {
dough.update();
buffers[0][dough.t] = dough.out[0];
buffers[1][dough.t] = dough.out[1];
if (dough.t % sampleRate === 0) {
process.stdout.write('.');
}
}
const took = (performance.now() - t) / 1000;
const load = (took / seconds) * 100;
const speed = (seconds / took).toFixed(2);
console.log('');
console.log(`done!
rendered ${seconds}s in ${took.toFixed(2)}s
speed: ${speed}x
load: ${load.toFixed(2)}%`);
const patternAudio = {
sampleRate,
channelData: buffers,
};
WavEncoder.encode(patternAudio).then((buffer) => {
fs.writeFileSync('pattern.wav', new Float32Array(buffer));
});
+39
View File
@@ -0,0 +1,39 @@
import { Dough } from './dough.mjs';
const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
class DoughProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.dough = new Dough(sampleRate, currentTime);
this.port.onmessage = (event) => {
if (event.data.spawn) {
this.dough.scheduleSpawn(event.data.spawn);
} else if (event.data.sample) {
this.dough.loadSample(event.data.sample, event.data.channels, event.data.sampleRate);
} else if (event.data.samples) {
event.data.samples.forEach(([name, channels, sampleRate]) => {
this.dough.loadSample(name, channels, sampleRate);
});
} else {
console.log('unrecognized event type', event.data);
}
};
}
process(inputs, outputs, params) {
if (this.disconnected) {
return false;
}
const output = outputs[0];
for (let i = 0; i < output[0].length; i++) {
this.dough.update();
for (let c = 0; c < output.length; c++) {
//prevent speaker blowout via clipping if threshold exceeds
output[c][i] = clamp(this.dough.out[c], -1, 1);
}
}
return true; // keep the audio processing going
}
}
registerProcessor('dough-processor', DoughProcessor);
+976
View File
@@ -0,0 +1,976 @@
// this is dough, the superdough without dependencies
const SAMPLE_RATE = typeof sampleRate !== 'undefined' ? sampleRate : 48000;
const PI_DIV_SR = Math.PI / SAMPLE_RATE;
const ISR = 1 / SAMPLE_RATE;
let gainCurveFunc = (val) => Math.pow(val, 2);
function applyGainCurve(val) {
return gainCurveFunc(val);
}
/**
* Equal Power Crossfade function.
* Smoothly transitions between signals A and B, maintaining consistent perceived loudness.
*
* @param {number} a - Signal A (can be a single value or an array value in buffer processing).
* @param {number} b - Signal B (can be a single value or an array value in buffer processing).
* @param {number} m - Crossfade parameter (0.0 = all A, 1.0 = all B, 0.5 = equal mix).
* @returns {number} Crossfaded output value.
*/
function crossfade(a, b, m) {
const aGain = Math.sin((1 - m) * 0.5 * Math.PI);
const bGain = Math.sin(m * 0.5 * Math.PI);
return a * aGain + b * bGain;
}
// function setGainCurve(newGainCurveFunc) {
// gainCurveFunc = newGainCurveFunc;
// }
// https://garten.salat.dev/audio-DSP/oscillators.html
export class SineOsc {
phase = 0;
update(freq) {
const value = Math.sin(this.phase * 2 * Math.PI);
this.phase = (this.phase + freq / SAMPLE_RATE) % 1;
return value;
}
}
export class ZawOsc {
phase = 0;
update(freq) {
this.phase += ISR * freq;
return (this.phase % 1) * 2 - 1;
}
}
function polyBlep(t, dt) {
// 0 <= t < 1
if (t < dt) {
t /= dt;
// 2 * (t - t^2/2 - 0.5)
return t + t - t * t - 1;
}
// -1 < t < 0
if (t > 1 - dt) {
t = (t - 1) / dt;
// 2 * (t^2/2 + t + 0.5)
return t * t + t + t + 1;
}
// 0 otherwise
return 0;
}
export class SawOsc {
constructor(props = {}) {
this.phase = props.phase ?? 0;
}
update(freq) {
const dt = freq / SAMPLE_RATE;
let p = polyBlep(this.phase, dt);
let s = 2 * this.phase - 1 - p;
this.phase += dt;
if (this.phase > 1) {
this.phase -= 1;
}
return s;
}
}
function getUnisonDetune(unison, detune, voiceIndex) {
if (unison < 2) {
return 0;
}
const lerp = (a, b, n) => {
return n * (b - a) + a;
};
return lerp(-detune * 0.5, detune * 0.5, voiceIndex / (unison - 1));
}
function applySemitoneDetuneToFrequency(frequency, detune) {
return frequency * Math.pow(2, detune / 12);
}
export class SupersawOsc {
constructor(props = {}) {
//TODO: figure out a good way to pass in these params
this.voices = props.voices ?? 5;
this.freqspread = props.freqspread ?? 0.2;
this.panspread = props.panspread ?? 0.4;
this.phase = new Float32Array(this.voices).map(() => Math.random());
}
update(freq) {
const gain1 = Math.sqrt(1 - this.panspread);
const gain2 = Math.sqrt(this.panspread);
let sl = 0;
let sr = 0;
for (let n = 0; n < this.voices; n++) {
const freqAdjusted = applySemitoneDetuneToFrequency(freq, getUnisonDetune(this.voices, this.freqspread, n));
const dt = freqAdjusted / SAMPLE_RATE;
const isOdd = (n & 1) == 1;
let gainL = gain1;
let gainR = gain2;
// invert right and left gain
if (isOdd) {
gainL = gain2;
gainR = gain1;
}
let p = polyBlep(this.phase[n], dt);
let s = 2 * this.phase[n] - 1 - p;
sl = sl + s * gainL;
sr = sr + s * gainL;
this.phase[n] += dt;
if (this.phase[n] > 1) {
this.phase[n] -= 1;
}
}
return sl + sr;
//TODO: make stereo
// return [sl, sr];
}
}
export class TriOsc {
phase = 0;
update(freq) {
this.phase += ISR * freq;
let phase = this.phase % 1;
let value = phase < 0.5 ? 2 * phase : 1 - 2 * (phase - 0.5);
return value * 2 - 1;
}
}
export class TwoPoleFilter {
s0 = 0;
s1 = 0;
update(s, cutoff, resonance = 0) {
// Out of bound values can produce NaNs
resonance = Math.max(resonance, 0);
cutoff = Math.min(cutoff, 20000);
const c = 2 * Math.sin(cutoff * PI_DIV_SR);
const r = Math.pow(0.5, (resonance + 0.125) / 0.125);
const mrc = 1 - r * c;
this.s0 = mrc * this.s0 - c * this.s1 + c * s; // bpf
this.s1 = mrc * this.s1 + c * this.s0; // lpf
return this.s1; // return lpf by default
}
}
class PulseOsc {
constructor(phase = 0) {
this.phase = phase;
}
saw(offset, dt) {
let phase = (this.phase + offset) % 1;
let p = polyBlep(phase, dt);
return 2 * phase - 1 - p;
}
update(freq, pw = 0.5) {
const dt = freq / SAMPLE_RATE;
let pulse = this.saw(0, dt) - this.saw(pw, dt);
this.phase = (this.phase + dt) % 1;
return pulse + pw * 2 - 1;
}
}
// non bandlimited (has aliasing)
export class PulzeOsc {
phase = 0;
update(freq, duty = 0.5) {
this.phase += ISR * freq;
let cyclePos = this.phase % 1;
return cyclePos < duty ? 1 : -1;
}
}
export class Dust {
update = (density) => (Math.random() < density * ISR ? Math.random() : 0);
}
export class WhiteNoise {
update() {
return Math.random() * 2 - 1;
}
}
export class BrownNoise {
constructor() {
this.out = 0;
}
update() {
let white = Math.random() * 2 - 1;
this.out = (this.out + 0.02 * white) / 1.02;
return this.out;
}
}
export class PinkNoise {
constructor() {
this.b0 = 0;
this.b1 = 0;
this.b2 = 0;
this.b3 = 0;
this.b4 = 0;
this.b5 = 0;
this.b6 = 0;
}
update() {
const white = Math.random() * 2 - 1;
this.b0 = 0.99886 * this.b0 + white * 0.0555179;
this.b1 = 0.99332 * this.b1 + white * 0.0750759;
this.b2 = 0.969 * this.b2 + white * 0.153852;
this.b3 = 0.8665 * this.b3 + white * 0.3104856;
this.b4 = 0.55 * this.b4 + white * 0.5329522;
this.b5 = -0.7616 * this.b5 - white * 0.016898;
const pink = this.b0 + this.b1 + this.b2 + this.b3 + this.b4 + this.b5 + this.b6 + white * 0.5362;
this.b6 = white * 0.115926;
return pink * 0.11;
}
}
export class Impulse {
phase = 1;
update(freq) {
this.phase += ISR * freq;
let v = this.phase >= 1 ? 1 : 0;
this.phase = this.phase % 1;
return v;
}
}
export class ClockDiv {
inSgn = true;
outSgn = true;
clockCnt = 0;
update(clock, factor) {
let curSgn = clock > 0;
if (this.inSgn != curSgn) {
this.clockCnt++;
if (this.clockCnt >= factor) {
this.clockCnt = 0;
this.outSgn = !this.outSgn;
}
}
this.inSgn = curSgn;
return this.outSgn ? 1 : -1;
}
}
export class Hold {
value = 0;
trigSgn = false;
update(input, trig) {
if (!this.trigSgn && trig > 0) this.value = input;
this.trigSgn = trig > 0;
return this.value;
}
}
function lerp(x, y0, y1, exponent = 1) {
if (x <= 0) return y0;
if (x >= 1) return y1;
let curvedX;
if (exponent === 0) {
curvedX = x; // linear
} else if (exponent > 0) {
curvedX = Math.pow(x, exponent); // ease-in
} else {
curvedX = 1 - Math.pow(1 - x, -exponent); // ease-out
}
return y0 + (y1 - y0) * curvedX;
}
export class ADSR {
constructor(props = {}) {
this.state = 'off';
this.startTime = 0;
this.startVal = 0;
this.decayCurve = props.decayCurve ?? 1;
}
update(curTime, gate, attack, decay, susVal, release) {
switch (this.state) {
case 'off': {
if (gate > 0) {
this.state = 'attack';
this.startTime = curTime;
this.startVal = 0;
}
return 0;
}
case 'attack': {
let time = curTime - this.startTime;
if (time > attack) {
this.state = 'decay';
this.startTime = curTime;
return 1;
}
return lerp(time / attack, this.startVal, 1, 1);
}
case 'decay': {
let time = curTime - this.startTime;
let curVal = lerp(time / decay, 1, susVal, -this.decayCurve);
if (gate <= 0) {
this.state = 'release';
this.startTime = curTime;
this.startVal = curVal;
return curVal;
}
if (time > decay) {
this.state = 'sustain';
this.startTime = curTime;
return susVal;
}
return curVal;
}
case 'sustain': {
if (gate <= 0) {
this.state = 'release';
this.startTime = curTime;
this.startVal = susVal;
}
return susVal;
}
case 'release': {
let time = curTime - this.startTime;
if (time > release) {
this.state = 'off';
return 0;
}
let curVal = lerp(time / release, this.startVal, 0, -this.decayCurve);
if (gate > 0) {
this.state = 'attack';
this.startTime = curTime;
this.startVal = curVal;
}
return curVal;
}
}
throw 'invalid envelope state';
}
}
/*
impulse(1).ad(.1).mul(sine(200))
.add(x=>x.delay(.1).mul(.8))
.out()*/
const MAX_DELAY_TIME = 10;
export class PitchDelay {
lpf = new TwoPoleFilter();
constructor(_props = {}) {
this.buffer = new Float32Array(MAX_DELAY_TIME * SAMPLE_RATE);
this.writeIdx = 0;
this.readIdx = 0;
this.numSamples = 0;
}
write(s, delayTime) {
// Calculate how far in the past to read
this.numSamples = Math.min(Math.floor(SAMPLE_RATE * delayTime), this.buffer.length - 1);
this.writeIdx = (this.writeIdx + 1) % this.numSamples;
this.buffer[this.writeIdx] = s;
this.readIdx = this.writeIdx - this.numSamples + 1;
// If past the start of the buffer, wrap around (Q: is this possible?)
if (this.readIdx < 0) this.readIdx += this.numSamples;
}
update(input, delayTime, speed = 1) {
this.write(input, delayTime);
let index = this.readIdx;
if (speed < 0) {
index = this.numSamples - Math.floor(Math.abs(this.readIdx * speed) % this.numSamples);
} else {
index = Math.floor(this.readIdx * speed) % this.numSamples;
}
const s = this.lpf.update(this.buffer[index], 0.9, 0);
return s;
}
}
export class Delay {
writeIdx = 0;
readIdx = 0;
buffer = new Float32Array(MAX_DELAY_TIME * SAMPLE_RATE); //.fill(0)
write(s, delayTime) {
this.writeIdx = (this.writeIdx + 1) % this.buffer.length;
this.buffer[this.writeIdx] = s;
// Calculate how far in the past to read
let numSamples = Math.min(Math.floor(SAMPLE_RATE * delayTime), this.buffer.length - 1);
this.readIdx = this.writeIdx - numSamples;
// If past the start of the buffer, wrap around
if (this.readIdx < 0) this.readIdx += this.buffer.length;
}
update(input, delayTime) {
this.write(input, delayTime);
return this.buffer[this.readIdx];
}
}
//TODO: Figure out why clicking at the start off the buffer
export class Chorus {
delay = new Delay();
modulator = new TriOsc();
update(input, mix, delayTime, modulationFreq, modulationDepth) {
const m = this.modulator.update(modulationFreq) * modulationDepth;
const c = this.delay.update(input, delayTime * (1 + m));
return crossfade(input, c, mix);
}
}
export class Fold {
update(input = 0, rate = 0) {
if (rate < 0) rate = 0;
rate = rate + 1;
input = input * rate;
return 4 * (Math.abs(0.25 * input + 0.25 - Math.round(0.25 * input + 0.25)) - 0.25);
}
}
export class Lag {
lagUnit = 4410;
s = 0;
update(input, rate) {
// Remap so the useful range is around [0, 1]
rate = rate * this.lagUnit;
if (rate < 1) rate = 1;
this.s += (1 / rate) * (input - this.s);
return this.s;
}
}
export class Slew {
last = 0;
update(input, up, dn) {
const upStep = up * ISR;
const downStep = dn * ISR;
let delta = input - this.last;
if (delta > upStep) {
delta = upStep;
} else if (delta < -downStep) {
delta = -downStep;
}
this.last += delta;
return this.last;
}
}
// overdrive style distortion (adapted from noisecraft) currently unused
export function applyDistortion(x, amount) {
amount = Math.min(Math.max(amount, 0), 1);
amount -= 0.01;
var k = (2 * amount) / (1 - amount);
var y = ((1 + k) * x) / (1 + k * Math.abs(x));
return y;
}
export class Sequence {
clockSgn = true;
step = 0;
first = true;
update(clock, ...ins) {
if (!this.clockSgn && clock > 0) {
this.step = (this.step + 1) % ins.length;
this.clockSgn = clock > 0;
return 0; // set first sample to zero to retrigger gates on step change...
}
this.clockSgn = clock > 0;
return ins[this.step];
}
}
// sample rate bit crusher
export class Coarse {
hold = 0;
t = 0;
update(input, coarse) {
if (this.t++ % coarse === 0) {
this.t = 0;
this.hold = input;
}
return this.hold;
}
}
// amplitude bit crusher
export class Crush {
update(input, crush) {
crush = Math.max(1, crush);
const x = Math.pow(2, crush - 1);
return Math.round(input * x) / x;
}
}
// this is the distort from superdough
export class Distort {
update(input, distort = 0, postgain = 1) {
postgain = Math.max(0.001, Math.min(1, postgain));
const shape = Math.expm1(distort);
return (((1 + shape) * input) / (1 + shape * Math.abs(input))) * postgain;
}
}
// distortion could be expressed as a function, because it's stateless
export class BufferPlayer {
static samples = new Map(); // string -> { channels, sampleRate }
buffer; // Float32Array
sampleRate;
pos = 0;
sampleFreq = note2freq();
constructor(buffer, sampleRate, normalize) {
this.buffer = buffer;
this.sampleRate = sampleRate;
this.duration = this.buffer.length / this.sampleRate;
this.speed = SAMPLE_RATE / this.sampleRate;
if (normalize) {
// this will make the buffer last 1s if freq = sampleFreq
// it's useful to loop samples (e.g. fit function)
this.speed *= this.duration;
}
}
update(freq) {
if (this.pos >= this.buffer.length) {
return 0;
}
const speed = (freq / this.sampleFreq) * this.speed;
let s = this.buffer[Math.floor(this.pos)];
this.pos = this.pos + speed;
return s;
}
}
export function _rangex(sig, min, max) {
let logmin = Math.log(min);
let range = Math.log(max) - logmin;
const unipolar = (sig + 1) / 2;
return Math.exp(unipolar * range + logmin);
}
// duplicate
export const getADSR = (params, curve = 'linear', defaultValues) => {
const envmin = curve === 'exponential' ? 0.001 : 0.001;
const releaseMin = 0.01;
const envmax = 1;
const [a, d, s, r] = params;
if (a == null && d == null && s == null && r == null) {
return defaultValues ?? [envmin, envmin, envmax, releaseMin];
}
const sustain = s != null ? s : (a != null && d == null) || (a == null && d == null) ? envmax : envmin;
return [Math.max(a ?? 0, envmin), Math.max(d ?? 0, envmin), Math.min(sustain, envmax), Math.max(r ?? 0, releaseMin)];
};
let shapes = {
sine: SineOsc,
saw: SawOsc,
zaw: ZawOsc,
sawtooth: SawOsc,
zawtooth: ZawOsc,
supersaw: SupersawOsc,
tri: TriOsc,
triangle: TriOsc,
pulse: PulseOsc,
square: PulseOsc,
pulze: PulzeOsc,
dust: Dust,
crackle: Dust,
impulse: Impulse,
white: WhiteNoise,
brown: BrownNoise,
pink: PinkNoise,
};
const defaultDefaultValues = {
chorus: 0,
note: 48,
s: 'triangle',
bank: '',
gain: 1,
postgain: 1,
velocity: 1,
density: '.03',
ftype: '12db',
fanchor: 0,
//resonance: 1, // superdough resonance is scaled differently
resonance: 0,
//hresonance: 1, // superdough resonance is scaled differently
hresonance: 0,
// bandq: 1, // superdough resonance is scaled differently
bandq: 0,
channels: [1, 2],
phaserdepth: 0.75,
shapevol: 1,
distortvol: 1,
delay: 0,
byteBeatExpression: '0',
delayfeedback: 0.5,
delayspeed: 1,
delaytime: 0.25,
orbit: 1,
i: 1,
fft: 8,
z: 'triangle',
pan: 0.5,
fmh: 1,
fmenv: 0, // differs from superdough
speed: 1,
pw: 0.5,
};
let getDefaultValue = (key) => defaultDefaultValues[key];
const chromas = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };
const accs = { '#': 1, b: -1, s: 1, f: -1 };
const note2midi = (note, defaultOctave = 3) => {
let [pc, acc = '', oct = ''] =
String(note)
.match(/^([a-gA-G])([#bsf]*)([0-9]*)$/)
?.slice(1) || [];
if (!pc) {
throw new Error('not a note: "' + note + '"');
}
const chroma = chromas[pc.toLowerCase()];
const offset = acc?.split('').reduce((o, char) => o + accs[char], 0) || 0;
oct = Number(oct || defaultOctave);
return (oct + 1) * 12 + chroma + offset;
};
const midi2freq = (midi) => Math.pow(2, (midi - 69) / 12) * 440;
const note2freq = (note) => {
note = note || getDefaultValue('note');
if (typeof note === 'string') {
note = note2midi(note, 3); // e.g. c3 => 48
}
return midi2freq(note);
};
export class DoughVoice {
out = [0, 0];
constructor(value) {
value.freq ??= note2freq(value.note);
let $ = this;
Object.assign($, value);
$.s = $.s ?? getDefaultValue('s');
$.gain = applyGainCurve($.gain ?? getDefaultValue('gain'));
$.velocity = applyGainCurve($.velocity ?? getDefaultValue('velocity'));
$.postgain = applyGainCurve($.postgain ?? getDefaultValue('postgain'));
$.density = $.density ?? getDefaultValue('density');
$.fanchor = $.fanchor ?? getDefaultValue('fanchor');
$.drive = $.drive ?? 0.69;
$.phaserdepth = $.phaserdepth ?? getDefaultValue('phaserdepth');
$.shapevol = applyGainCurve($.shapevol ?? getDefaultValue('shapevol'));
$.distortvol = applyGainCurve($.distortvol ?? getDefaultValue('distortvol'));
$.i = $.i ?? getDefaultValue('i');
$.chorus = $.chorus ?? getDefaultValue('chorus');
$.fft = $.fft ?? getDefaultValue('fft');
$.pan = $.pan ?? getDefaultValue('pan');
$.orbit = $.orbit ?? getDefaultValue('orbit');
$.fmenv = $.fmenv ?? getDefaultValue('fmenv');
$.resonance = $.resonance ?? getDefaultValue('resonance');
$.hresonance = $.hresonance ?? getDefaultValue('hresonance');
$.bandq = $.bandq ?? getDefaultValue('bandq');
$.speed = $.speed ?? getDefaultValue('speed');
$.pw = $.pw ?? getDefaultValue('pw');
[$.attack, $.decay, $.sustain, $.release] = getADSR([$.attack, $.decay, $.sustain, $.release]);
$._holdEnd = $._begin + $._duration; // needed for gate
$._end = $._holdEnd + $.release + 0.01; // needed for despawn
if ($.fmi && ($.s === 'saw' || $.s === 'sawtooth')) {
$.s = 'zaw'; // polyblepped saw when fm is applied
}
if (shapes[$.s]) {
const SourceClass = shapes[$.s];
$._sound = new SourceClass();
$._channels = 1;
} else if (BufferPlayer.samples.has($.s)) {
const sample = BufferPlayer.samples.get($.s);
$._buffers = [];
$._channels = sample.channels.length;
for (let i = 0; i < $._channels; i++) {
$._buffers.push(new BufferPlayer(sample.channels[i], sample.sampleRate, $.unit === 'c')); // tbd unit === 'c'
}
} else {
console.warn('sound not loaded', $.s);
}
if ($.penv) {
$._penv = new ADSR({ decayCurve: 4 });
[$.pattack, $.pdecay, $.psustain, $.prelease] = getADSR([$.pattack, $.pdecay, $.psustain, $.prelease]);
}
if ($.vib) {
$._vib = new SineOsc();
$.vibmod = $.vibmod ?? getDefaultValue('vibmod');
}
if ($.fmi) {
$._fm = new SineOsc();
$.fmh = $.fmh ?? getDefaultValue('fmh');
if ($.fmenv) {
$._fmenv = new ADSR({ decayCurve: 2 });
[$.fmattack, $.fmdecay, $.fmsustain, $.fmrelease] = getADSR([$.fmattack, $.fmdecay, $.fmsustain, $.fmrelease]);
}
}
// gain envelope
$._adsr = new ADSR({ decayCurve: 2 });
// delay
$.delay = applyGainCurve($.delay ?? getDefaultValue('delay'));
$.delayfeedback = $.delayfeedback ?? getDefaultValue('delayfeedback');
$.delayspeed = $.delayspeed ?? getDefaultValue('delayspeed');
$.delaytime = $.delaytime ?? getDefaultValue('delaytime');
// filter setup
if ($.lpenv) {
$._lpenv = new ADSR({ decayCurve: 4 });
[$.lpattack, $.lpdecay, $.lpsustain, $.lprelease] = getADSR([$.lpattack, $.lpdecay, $.lpsustain, $.lprelease]);
}
if ($.hpenv) {
$._hpenv = new ADSR({ decayCurve: 4 });
[$.hpattack, $.hpdecay, $.hpsustain, $.hprelease] = getADSR([$.hpattack, $.hpdecay, $.hpsustain, $.hprelease]);
}
if ($.bpenv) {
$._bpenv = new ADSR({ decayCurve: 4 });
[$.bpattack, $.bpdecay, $.bpsustain, $.bprelease] = getADSR([$.bpattack, $.bpdecay, $.bpsustain, $.bprelease]);
}
// channelwise effects setup
$._chorus = $.chorus ? [] : null;
$._lpf = $.cutoff ? [] : null;
$._hpf = $.hcutoff ? [] : null;
$._bpf = $.bandf ? [] : null;
$._coarse = $.coarse ? [] : null;
$._crush = $.crush ? [] : null;
$._distort = $.distort ? [] : null;
for (let i = 0; i < this._channels; i++) {
$._lpf?.push(new TwoPoleFilter());
$._hpf?.push(new TwoPoleFilter());
$._bpf?.push(new TwoPoleFilter());
$._chorus?.push(new Chorus());
$._coarse?.push(new Coarse());
$._crush?.push(new Crush());
$._distort?.push(new Distort());
}
}
update(t) {
if (!this._sound && !this._buffers) {
return 0;
}
let gate = Number(t >= this._begin && t <= this._holdEnd);
let freq = this.freq * this.speed;
// frequency modulation
if (this._fm) {
let fmi = this.fmi;
if (this._fmenv) {
const env = this._fmenv.update(t, gate, this.fmattack, this.fmdecay, this.fmsustain, this.fmrelease);
fmi = this.fmenv * env * fmi;
}
const modfreq = freq * this.fmh;
const modgain = modfreq * fmi;
freq = freq + this._fm.update(modfreq) * modgain;
}
// vibrato
if (this._vib) {
freq = freq * 2 ** ((this._vib.update(this.vib) * this.vibmod) / 12);
}
// pitch envelope
if (this._penv) {
const env = this._penv.update(t, gate, this.pattack, this.pdecay, this.psustain, this.prelease);
freq = freq + env * this.penv;
}
// filters
let lpf = this.cutoff;
if (this._lpf) {
if (this._lpenv) {
const env = this._lpenv.update(t, gate, this.lpattack, this.lpdecay, this.lpsustain, this.lprelease);
lpf = this.lpenv * env * lpf + lpf;
}
}
let hpf = this.hcutoff;
if (this._hpf) {
if (this._hpenv) {
const env = this._hpenv.update(t, gate, this.hpattack, this.hpdecay, this.hpsustain, this.hprelease);
hpf = 2 ** this.hpenv * env * hpf + hpf;
}
}
let bpf = this.bandf;
if (this._bpf) {
if (this._bpenv) {
const env = this._bpenv.update(t, gate, this.bpattack, this.bpdecay, this.bpsustain, this.bprelease);
bpf = 2 ** this.bpenv * env * bpf + bpf;
}
}
// gain envelope
const env = this._adsr.update(t, gate, this.attack, this.decay, this.sustain, this.release);
// channelwise dsp
for (let i = 0; i < this._channels; i++) {
// sound source
if (this._sound && this.s === 'pulse') {
this.out[i] = this._sound.update(freq, this.pw);
} else if (this._sound) {
this.out[i] = this._sound.update(freq);
} else if (this._buffers) {
this.out[i] = this._buffers[i].update(freq);
}
this.out[i] = this.out[i] * this.gain * this.velocity;
if (this._chorus) {
const c = this._chorus[i].update(this.out[i], this.chorus, 0.03 + 0.05 * i, 1, 0.11);
this.out[i] = c + this.out[i];
}
if (this._lpf) {
this._lpf[i].update(this.out[i], lpf, this.resonance);
this.out[i] = this._lpf[i].s1;
}
if (this._hpf) {
this._hpf[i].update(this.out[i], hpf, this.hresonance);
this.out[i] = this.out[i] - this._hpf[i].s1;
}
if (this._bpf) {
this._bpf[i].update(this.out[i], bpf, this.bandq);
this.out[i] = this._bpf[i].s0;
}
if (this._coarse) {
this.out[i] = this._coarse[i].update(this.out[i], this.coarse);
}
if (this._crush) {
this.out[i] = this._crush[i].update(this.out[i], this.crush);
}
if (this._distort) {
this.out[i] = this._distort[i].update(this.out[i], this.distort, this.distortvol);
}
this.out[i] = this.out[i] * env;
this.out[i] = this.out[i] * this.postgain;
if (!this._buffers) {
this.out[i] = this.out[i] * 0.2; // turn down waveform
}
}
if (this._channels === 1) {
this.out[1] = this.out[0];
}
if (this.pan !== 0.5) {
const panpos = (this.pan * Math.PI) / 2;
this.out[0] = this.out[0] * Math.cos(panpos);
this.out[1] = this.out[1] * Math.sin(panpos);
}
}
}
// this class is the interface to the "outer world"
// it handles spawning and despawning of DoughVoice's
export class Dough {
voices = []; // DoughVoice[]
vid = 0;
q = [];
out = [0, 0];
delaysend = [0, 0];
delaytime = getDefaultValue('delaytime');
delayfeedback = getDefaultValue('delayfeedback');
delayspeed = getDefaultValue('delayspeed');
t = 0;
// sampleRate: number, currentTime: number (seconds)
constructor(sampleRate = 48000, currentTime = 0) {
this.sampleRate = sampleRate;
this.t = Math.floor(currentTime * sampleRate); // samples
// console.log('init dough', this.sampleRate, this.t);
this._delayL = new PitchDelay();
this._delayR = new PitchDelay();
}
loadSample(name, channels, sampleRate) {
BufferPlayer.samples.set(name, { channels, sampleRate });
}
scheduleSpawn(value) {
if (value._begin === undefined) {
throw new Error('[dough]: scheduleSpawn expected _begin to be set');
}
if (value._duration === undefined) {
throw new Error('[dough]: scheduleSpawn expected _duration to be set');
}
value.sampleRate = this.sampleRate;
// convert seconds to samples
const time = Math.floor(value._begin * this.sampleRate); // set from supradough.mjs
this.schedule({ time, type: 'spawn', arg: value });
}
spawn(value) {
value.id = this.vid++;
const voice = new DoughVoice(value);
this.voices.push(voice);
// console.log('spawn', voice.id, 'voices:', this.voices.length);
// schedule removal
const endTime = Math.ceil(voice._end * this.sampleRate);
this.schedule({ time: endTime /* + 48000 */, type: 'despawn', arg: voice.id });
}
despawn(vid) {
this.voices = this.voices.filter((v) => v.id !== vid);
// console.log('despawn', vid, 'voices:', this.voices.length);
}
// schedules a function call with a single argument
// msg = {time:number,type:string, arg: any}
// the Dough method "type" will be called with "arg" at "time"
schedule(msg) {
if (!this.q.length) {
// if empty, just push
this.q.push(msg);
return;
}
// not empty
// find index where msg.time fits in
let i = 0;
while (i < this.q.length && this.q[i].time < msg.time) {
i++;
}
// this ensures q stays sorted by time, so we only need to check q[0]
this.q.splice(i, 0, msg);
}
// maybe update should be called once per block instead for perf reasons?
update() {
// go over q
while (this.q.length > 0 && this.q[0].time <= this.t) {
// console.log('schedule', this.q[0]);
// trigger due messages. q is sorted, so we only need to check q[0]
this[this.q[0].type](this.q[0].arg); // type is expected to be a Dough method
this.q.shift();
}
// add active voices
this.out[0] = 0;
this.out[1] = 0;
for (let v = 0; v < this.voices.length; v++) {
this.voices[v].update(this.t / this.sampleRate);
this.out[0] += this.voices[v].out[0];
this.out[1] += this.voices[v].out[1];
if (this.voices[v].delay) {
this.delaysend[0] += this.voices[v].out[0] * this.voices[v].delay;
this.delaysend[1] += this.voices[v].out[1] * this.voices[v].delay;
this.delaytime = this.voices[v].delaytime; // we trust that these are initialized in the voice
this.delayspeed = this.voices[v].delayspeed; // we trust that these are initialized in the voice
this.delayfeedback = this.voices[v].delayfeedback;
}
}
// todo: how to change delaytime / delayfeedback from a voice?
const delayL = this._delayL.update(this.delaysend[0], this.delaytime, this.delayspeed);
const delayR = this._delayR.update(this.delaysend[1], this.delaytime, this.delayspeed);
this.delaysend[0] = delayL * this.delayfeedback;
this.delaysend[1] = delayR * this.delayfeedback;
this.out[0] += delayL;
this.out[1] += delayR;
this.t++;
}
}
+4
View File
@@ -0,0 +1,4 @@
import _workletUrl from './dough-worklet.mjs?url'; // todo: change ?url to ?audioworklet before build (?audioworklet doesn't hot reload)
export * from './dough.mjs';
export const workletUrl = _workletUrl;
+37
View File
@@ -0,0 +1,37 @@
{
"name": "supradough",
"version": "1.2.3",
"description": "platform agnostic synth and sampler intended for live coding. a reimplementation of superdough.",
"main": "index.mjs",
"type": "module",
"publishConfig": {
"main": "dist/index.mjs"
},
"scripts": {
"build": "vite build",
"prepublishOnly": "npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/tidalcycles/strudel.git"
},
"keywords": [
"tidalcycles",
"strudel",
"pattern",
"livecoding",
"algorave"
],
"author": "Felix Roos <flix91@gmail.com>",
"license": "AGPL-3.0-or-later",
"bugs": {
"url": "https://github.com/tidalcycles/strudel/issues"
},
"homepage": "https://github.com/tidalcycles/strudel#readme",
"devDependencies": {
"vite": "^6.0.11",
"vite-plugin-bundle-audioworklet": "workspace:*",
"wav-encoder": "^1.3.0"
},
"dependencies": {}
}
+1
View File
@@ -7,4 +7,5 @@ This program is free software: you can redistribute it and/or modify it under th
export * from './webaudio.mjs';
export * from './scope.mjs';
export * from './spectrum.mjs';
export * from './supradough.mjs';
export * from 'superdough';
+2 -1
View File
@@ -35,7 +35,8 @@
"dependencies": {
"@strudel/core": "workspace:*",
"@strudel/draw": "workspace:*",
"superdough": "workspace:*"
"superdough": "workspace:*",
"supradough": "workspace:*"
},
"devDependencies": {
"vite": "^6.0.11"
+130
View File
@@ -0,0 +1,130 @@
import { Pattern } from '@strudel/core';
import { connectToDestination, getAudioContext, getWorklet } from 'superdough';
let doughWorklet;
function initDoughWorklet() {
const ac = getAudioContext();
doughWorklet = getWorklet(
ac,
'dough-processor',
{},
{
outputChannelCount: [2],
},
);
connectToDestination(doughWorklet); // channels?
}
const soundMap = new Map();
const loadedSounds = new Map();
Pattern.prototype.supradough = function () {
return this.onTrigger((hap, __, cps, begin) => {
hap.value._begin = begin;
hap.value._duration = hap.duration / cps;
!doughWorklet && initDoughWorklet();
const s = (hap.value.bank ? hap.value.bank + '_' : '') + hap.value.s;
const n = hap.value.n ?? 0;
const soundKey = `${s}:${n}`;
if (soundMap.has(s)) {
hap.value.s = soundKey; // dough.mjs is unaware of bank and n (only maps keys to buffers)
}
if (soundMap.has(s) && !loadedSounds.has(soundKey)) {
const urls = soundMap.get(s);
const url = urls[n % urls.length];
console.log(`load ${soundKey} from ${url}`);
const loadSample = fetchSample(url);
loadedSounds.set(soundKey, loadSample);
loadSample.then(({ channels, sampleRate }) =>
doughWorklet.port.postMessage({
sample: soundKey,
channels,
sampleRate,
}),
);
}
doughWorklet.port.postMessage({ spawn: hap.value });
}, 1);
};
function githubPath(base, subpath = '') {
if (!base.startsWith('github:')) {
throw new Error('expected "github:" at the start of pseudoUrl');
}
let [_, path] = base.split('github:');
path = path.endsWith('/') ? path.slice(0, -1) : path;
if (path.split('/').length === 2) {
// assume main as default branch if none set
path += '/main';
}
return `https://raw.githubusercontent.com/${path}/${subpath}`;
}
export async function fetchSampleMap(url) {
if (url.startsWith('github:')) {
url = githubPath(url, 'strudel.json');
}
if (url.startsWith('local:')) {
url = `http://localhost:5432`;
}
if (url.startsWith('shabda:')) {
let [_, path] = url.split('shabda:');
url = `https://shabda.ndre.gr/${path}.json?strudel=1`;
}
if (url.startsWith('shabda/speech')) {
let [_, path] = url.split('shabda/speech');
path = path.startsWith('/') ? path.substring(1) : path;
let [params, words] = path.split(':');
let gender = 'f';
let language = 'en-GB';
if (params) {
[language, gender] = params.split('/');
}
url = `https://shabda.ndre.gr/speech/${words}.json?gender=${gender}&language=${language}&strudel=1'`;
}
if (typeof fetch !== 'function') {
// not a browser
return;
}
const base = url.split('/').slice(0, -1).join('/');
if (typeof fetch === 'undefined') {
// skip fetch when in node / testing
return;
}
const json = await fetch(url)
.then((res) => res.json())
.catch((error) => {
console.error(error);
throw new Error(`error loading "${url}"`);
});
return [json, json._base || base];
}
// for some reason, only piano and flute work.. is it because mp3??
async function fetchSample(url) {
const buffer = await fetch(url)
.then((res) => res.arrayBuffer())
.then((buf) => getAudioContext().decodeAudioData(buf));
let channels = [];
for (let i = 0; i < buffer.numberOfChannels; i++) {
channels.push(buffer.getChannelData(i));
}
return { channels, sampleRate: buffer.sampleRate };
}
export async function doughsamples(sampleMap, baseUrl) {
if (typeof sampleMap === 'string') {
const [json, base] = await fetchSampleMap(sampleMap);
// console.log('json', json, 'base', base);
return doughsamples(json, base);
}
Object.entries(sampleMap).map(async ([key, urls]) => {
if (key !== '_base') {
urls = urls.map((url) => baseUrl + url);
// console.log('set', key, urls);
soundMap.set(key, urls);
}
});
}
+6 -1
View File
@@ -5,7 +5,12 @@ This program is free software: you can redistribute it and/or modify it under th
*/
import * as strudel from '@strudel/core';
import { superdough, getAudioContext, setLogger, doughTrigger } from 'superdough';
import { superdough, getAudioContext, setLogger, doughTrigger, registerWorklet } from 'superdough';
import './supradough.mjs';
import { workletUrl } from 'supradough';
registerWorklet(workletUrl);
const { Pattern, logger, repl } = strudel;
setLogger(logger);
+20
View File
@@ -517,6 +517,18 @@ importers:
specifier: workspace:*
version: link:../vite-plugin-bundle-audioworklet
packages/supradough:
devDependencies:
vite:
specifier: ^6.0.11
version: 6.0.11(@types/node@22.10.10)(jiti@2.4.2)(lightningcss@1.29.1)(terser@5.37.0)(yaml@2.7.0)
vite-plugin-bundle-audioworklet:
specifier: workspace:*
version: link:../vite-plugin-bundle-audioworklet
wav-encoder:
specifier: ^1.3.0
version: 1.3.0
packages/tidal:
dependencies:
'@strudel/core':
@@ -625,6 +637,9 @@ importers:
superdough:
specifier: workspace:*
version: link:../superdough
supradough:
specifier: workspace:*
version: link:../supradough
devDependencies:
vite:
specifier: ^6.0.11
@@ -7535,6 +7550,9 @@ packages:
walk-up-path@3.0.1:
resolution: {integrity: sha512-9YlCL/ynK3CTlrSRrDxZvUauLzAswPCrsaCgilqFevUYpeEW0/3ScEjaa3kbW/T0ghhkEr7mv+fpjqn1Y1YuTA==}
wav-encoder@1.3.0:
resolution: {integrity: sha512-FXJdEu2qDOI+wbVYZpu21CS1vPEg5NaxNskBr4SaULpOJMrLE6xkH8dECa7PiS+ZoeyvP7GllWUAxPN3AvFSEw==}
wav@1.0.2:
resolution: {integrity: sha512-viHtz3cDd/Tcr/HbNqzQCofKdF6kWUymH9LGDdskfWFoIy/HJ+RTihgjEcHfnsy1PO4e9B+y4HwgTwMrByquhg==}
@@ -15955,6 +15973,8 @@ snapshots:
walk-up-path@3.0.1: {}
wav-encoder@1.3.0: {}
wav@1.0.2:
dependencies:
buffer-alloc: 1.2.0
+67 -13
View File
@@ -1847,6 +1847,27 @@ exports[`runs examples > example "chop" example index 0 1`] = `
]
`;
exports[`runs examples > example "chorus" example index 0 1`] = `
[
"[ 0/1 → 1/4 | note:d s:sawtooth chorus:0.5 ]",
"[ 1/4 → 1/2 | note:d s:sawtooth chorus:0.5 ]",
"[ 1/2 → 3/4 | note:a# s:sawtooth chorus:0.5 ]",
"[ 3/4 → 1/1 | note:a s:sawtooth chorus:0.5 ]",
"[ 1/1 → 5/4 | note:d s:sawtooth chorus:0.5 ]",
"[ 5/4 → 3/2 | note:d s:sawtooth chorus:0.5 ]",
"[ 3/2 → 7/4 | note:a# s:sawtooth chorus:0.5 ]",
"[ 7/4 → 2/1 | note:a s:sawtooth chorus:0.5 ]",
"[ 2/1 → 9/4 | note:d s:sawtooth chorus:0.5 ]",
"[ 9/4 → 5/2 | note:d s:sawtooth chorus:0.5 ]",
"[ 5/2 → 11/4 | note:a# s:sawtooth chorus:0.5 ]",
"[ 11/4 → 3/1 | note:a s:sawtooth chorus:0.5 ]",
"[ 3/1 → 13/4 | note:d s:sawtooth chorus:0.5 ]",
"[ 13/4 → 7/2 | note:d s:sawtooth chorus:0.5 ]",
"[ 7/2 → 15/4 | note:a# s:sawtooth chorus:0.5 ]",
"[ 15/4 → 4/1 | note:a s:sawtooth chorus:0.5 ]",
]
`;
exports[`runs examples > example "chunk" example index 0 1`] = `
[
"[ 0/1 → 1/4 | note:A4 ]",
@@ -2585,6 +2606,52 @@ exports[`runs examples > example "delayfeedback" example index 0 1`] = `
]
`;
exports[`runs examples > example "delayfeedback" example index 0 2`] = `
[
"[ 0/1 → 1/1 | s:bd delay:0.25 delayfeedback:0.25 ]",
"[ 1/1 → 2/1 | s:bd delay:0.25 delayfeedback:0.5 ]",
"[ 2/1 → 3/1 | s:bd delay:0.25 delayfeedback:0.75 ]",
"[ 3/1 → 4/1 | s:bd delay:0.25 delayfeedback:1 ]",
]
`;
exports[`runs examples > example "delayspeed" example index 0 1`] = `
[
"[ 0/1 → 1/8 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:2 ]",
"[ 1/8 → 1/4 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:2 ]",
"[ 1/4 → 3/8 | note:a# s:sawtooth delay:0.8 delaytime:0.5 delayspeed:2 ]",
"[ 3/8 → 1/2 | note:a s:sawtooth delay:0.8 delaytime:0.5 delayspeed:2 ]",
"[ 1/2 → 5/8 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:2 ]",
"[ 5/8 → 3/4 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:2 ]",
"[ 3/4 → 7/8 | note:a# s:sawtooth delay:0.8 delaytime:0.5 delayspeed:2 ]",
"[ 7/8 → 1/1 | note:a s:sawtooth delay:0.8 delaytime:0.5 delayspeed:2 ]",
"[ 1/1 → 9/8 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:0.5 ]",
"[ 9/8 → 5/4 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:0.5 ]",
"[ 5/4 → 11/8 | note:a# s:sawtooth delay:0.8 delaytime:0.5 delayspeed:0.5 ]",
"[ 11/8 → 3/2 | note:a s:sawtooth delay:0.8 delaytime:0.5 delayspeed:0.5 ]",
"[ 3/2 → 13/8 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:0.5 ]",
"[ 13/8 → 7/4 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:0.5 ]",
"[ 7/4 → 15/8 | note:a# s:sawtooth delay:0.8 delaytime:0.5 delayspeed:0.5 ]",
"[ 15/8 → 2/1 | note:a s:sawtooth delay:0.8 delaytime:0.5 delayspeed:0.5 ]",
"[ 2/1 → 17/8 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-1 ]",
"[ 17/8 → 9/4 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-1 ]",
"[ 9/4 → 19/8 | note:a# s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-1 ]",
"[ 19/8 → 5/2 | note:a s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-1 ]",
"[ 5/2 → 21/8 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-1 ]",
"[ 21/8 → 11/4 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-1 ]",
"[ 11/4 → 23/8 | note:a# s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-1 ]",
"[ 23/8 → 3/1 | note:a s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-1 ]",
"[ 3/1 → 25/8 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-2 ]",
"[ 25/8 → 13/4 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-2 ]",
"[ 13/4 → 27/8 | note:a# s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-2 ]",
"[ 27/8 → 7/2 | note:a s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-2 ]",
"[ 7/2 → 29/8 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-2 ]",
"[ 29/8 → 15/4 | note:d s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-2 ]",
"[ 15/4 → 31/8 | note:a# s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-2 ]",
"[ 31/8 → 4/1 | note:a s:sawtooth delay:0.8 delaytime:0.5 delayspeed:-2 ]",
]
`;
exports[`runs examples > example "delaysync" example index 0 1`] = `
[
"[ 0/1 → 1/2 | s:bd delay:0.25 delaysync:0.125 ]",
@@ -2598,19 +2665,6 @@ exports[`runs examples > example "delaysync" example index 0 1`] = `
]
`;
exports[`runs examples > example "delaytime" example index 0 1`] = `
[
"[ 0/1 → 1/2 | s:bd delay:0.25 delaytime:0.125 ]",
"[ 1/2 → 1/1 | s:bd delay:0.25 delaytime:0.125 ]",
"[ 1/1 → 3/2 | s:bd delay:0.25 delaytime:0.25 ]",
"[ 3/2 → 2/1 | s:bd delay:0.25 delaytime:0.25 ]",
"[ 2/1 → 5/2 | s:bd delay:0.25 delaytime:0.5 ]",
"[ 5/2 → 3/1 | s:bd delay:0.25 delaytime:0.5 ]",
"[ 3/1 → 7/2 | s:bd delay:0.25 delaytime:1 ]",
"[ 7/2 → 4/1 | s:bd delay:0.25 delaytime:1 ]",
]
`;
exports[`runs examples > example "density" example index 0 1`] = `
[
"[ 0/1 → 1/4 | s:crackle density:0.01 ]",
+1 -2
View File
@@ -8,8 +8,7 @@
"start": "astro dev",
"build": "astro build",
"preview": "astro preview --port 3009 --host 0.0.0.0",
"astro": "astro",
"postinstall": "cp node_modules/hs2js/dist/tree-sitter.wasm public && cp node_modules/hs2js/dist/tree-sitter-haskell.wasm public"
"astro": "astro"
},
"dependencies": {
"@algolia/client-search": "^5.20.0",
@@ -34,11 +34,11 @@ import { JsDoc } from '../../docs/JsDoc';
## arp
<JsDoc client:idle name="Pattern#arp" h={0} />
<JsDoc client:idle name="arp" h={0} />
## arpWith 🧪
<JsDoc client:idle name="Pattern#arpWith" h={0} />
<JsDoc client:idle name="arpWith" h={0} />
## struct
@@ -58,7 +58,7 @@ import { JsDoc } from '../../docs/JsDoc';
## hush
<JsDoc client:idle name="hush" h={0} />
<JsDoc client:idle name="Pattern#hush" h={0} />
## invert
+14
View File
@@ -339,4 +339,18 @@ global effects use the same chain for all events of the same orbit:
<JsDoc client:idle name="phasersweep" h={0} />
## Duck
### duckorbit
<JsDoc client:idle name="duckorbit" h={0} />
### duckattack
<JsDoc client:idle name="duckattack" h={0} />
### duckdepth
<JsDoc client:idle name="duckdepth" h={0} />
Next, we'll look at input / output via [MIDI, OSC and other methods](/learn/input-output).
+14
View File
@@ -178,6 +178,16 @@ the version number).
It is also possible, of course, to just remove it from cache (deleting cache in browser Privacy settings,
or from the dev console if you're technically minded, or by using a cache deleting extension).
## Generating strudel.json
You can use [@strudel/sampler](https://www.npmjs.com/package/@strudel/sampler) to generate a strudel.json file for you, by running:
```sh
npx --yes @strudel/sampler --json > strudel.json
```
See other uses of strudel/sampler further below, under "From Disk via @strudel/sampler".
## Github Shortcut
Because loading samples from github is common, there is a shortcut:
@@ -361,6 +371,10 @@ Sampler effects are functions that can be used to change the behaviour of sample
<JsDoc client:idle name="splice" h={0} />
### scrub
<JsDoc client:idle name="Pattern.scrub" h={0} />{' '}
### speed
<JsDoc client:idle name="speed" h={0} />
+130
View File
@@ -69,3 +69,133 @@
text-decoration: underline 0.18rem;
text-underline-offset: 0.22rem;
}
/* Override default styles from the codemirror inline css for autocomplete info tooltip*/
.cm-tooltip.cm-completionInfo {
padding: 12px !important;
padding-bottom: 12px !important;
border: 1px solid var(--foreground) !important;
border-radius: 4px !important;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
max-width: 500px !important;
min-width: 300px !important;
max-height: 400px !important;
white-space: normal !important;
overflow: auto !important;
background-color: var(--lineHighlight) !important;
}
/* Main tooltip container */
.autocomplete-info-tooltip {
border-radius: 4px !important;
color: var(--foreground);
font-family: var(--font-family, 'SF Mono', 'Monaco', monospace);
font-size: var(--font-size, 13px);
line-height: 1.4;
max-width: 600px;
max-height: 400px;
min-width: 400px;
}
.autocomplete-info-function-name {
font-size: 15px;
font-weight: 600;
color: var(--foreground);
margin: 0 0 8px 0;
}
.autocomplete-info-function-description {
margin: 0 0 12px 0;
color: var(--foreground);
line-height: 1.5;
opacity: 0.8;
}
.autocomplete-info-section-title {
font-size: 12px;
font-weight: 600;
color: var(--foreground);
margin: 16px 0 6px 0;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.autocomplete-info-section-title:first-child {
margin-top: 0;
}
.autocomplete-info-params-section {
margin-top: 12px;
}
.autocomplete-info-params-list {
list-style: none;
margin: 0;
padding: 0;
}
.autocomplete-info-param-item {
margin-bottom: 8px;
padding: 8px;
background-color: var(--lineBackground);
border-radius: 3px;
border-left: 2px solid var(--foreground, #555);
}
.autocomplete-info-param-item:last-child {
margin-bottom: 0;
}
.autocomplete-info-param-name {
font-weight: 600;
color: var(--variable, var(--foreground));
margin-right: 8px;
}
.autocomplete-info-param-type {
color: var(--comment);
font-size: 12px;
background-color: var(--gutterForeground);
padding: 1px 4px;
border-radius: 2px;
}
.autocomplete-info-param-desc {
color: var(--foreground);
font-size: 10px;
margin-top: 4px;
line-height: 1.4;
opacity: 0.7;
}
.autocomplete-info-examples-section {
margin-top: 12px;
}
.autocomplete-info-example-code {
background: var(--lineBackground);
color: var(--foreground);
padding: 8px;
border-radius: 3px;
font-family: var(--font-family, 'SF Mono', 'Monaco', monospace);
font-size: 12px;
line-height: 1.5;
margin: 4px 0;
overflow-x: auto;
white-space: pre;
border: 1px solid var(--foreground, #3a3a3a);
}
.autocomplete-info-tooltip::-webkit-scrollbar {
width: 4px;
}
.autocomplete-info-tooltip::-webkit-scrollbar-track {
}
.autocomplete-info-tooltip::-webkit-scrollbar-thumb {
border-radius: 2px;
}
.autocomplete-info-tooltip::-webkit-scrollbar-thumb:hover {
}