Create a Live Coding Music App · Part 7 of 18 in the series
Part 7: Choices, Polymeter and Changing Speeds
Finish the mini-notation: a choice between several sequences that is made anew in every cycle, layers of different length that drift against each other, and speeds that change from cycle to cycle. The part ends with a reference of every symbol.
Create a Live Coding Music AppPart 7 of 18
On this page
Quest objectives
- Cut a stretch of time at its cycle borders and ask a different pattern in each cycle
- Pick one of several sequences per cycle by chance
- Run layers of different length side by side as a polymeter
- Change the speed of a step from cycle to cycle
- Look up every symbol of the notation in one list
The notation of part 6 can repeat steps, stretch them and thin them out. Three things are still missing: deciding between whole alternatives, running layers of different length side by side, and changing a speed from one cycle to the next. This part adds them, and with them the language is complete. There is little new code: two small functions over the patterns of part 4, plus a few lines in the parser and the compiler.
A different pattern in each cycle
Two of the three need the same thing: several patterns, of which one plays per cycle. A pattern is asked for a stretch of cycles and answers with the events that begin in it, and the stretch can be anything. The clock asks for small slices, and now and then a slice reaches across the border between two cycles. fast asks for stretches that are several cycles long. So before one pattern per cycle can be picked, the stretch has to be cut at the cycle borders. In src/pattern.ts, add a helper at the end of the file:
/** Calls `visit` for every cycle a stretch touches, with the part of the stretch inside it. */
function eachCycle(begin: number, end: number, visit: (cycle: number, from: number, to: number) => void) {
for (let cycle = Math.floor(snap(begin)); cycle < snap(end); cycle += 1) {
const from = Math.max(begin, cycle);
const to = Math.min(end, cycle + 1);
if (snap(from) < snap(to)) visit(cycle, from, to);
}
}For the stretch from 0.9 to 2.1 it calls visit three times: for cycle 0 with 0.9 to 1, for cycle 1 with 1 to 2, and for cycle 2 with 2 to 2.1. The comparisons go through snap from part 4, so a piece that exists only as floating point noise is left out. Below the helper, add the two functions that use it:
/** One of several patterns per cycle, taking turns: the same pattern at a speed per cycle. */
export function takeTurns<T>(patterns: Pattern<T>[]): Pattern<T> {
if (patterns.length === 1) return patterns[0];
return (begin, end) => {
const haps: Hap<T>[] = [];
eachCycle(begin, end, (cycle, from, to) => {
haps.push(...patterns[cycle % patterns.length](from, to));
});
return haps;
};
}
/** One of several patterns per cycle, picked by chance. */
export function choose<T>(patterns: Pattern<T>[], seed: number): Pattern<T> {
return (begin, end) => {
const haps: Hap<T>[] = [];
eachCycle(begin, end, (cycle, from, to) => {
const pick = Math.floor(random(cycle + 0.5, seed) * patterns.length);
haps.push(...patterns[pick](from, to));
});
return haps;
};
}takeTurns picks by the number of the cycle. With two patterns, the first plays in cycles 0, 2 and 4, the second in cycles 1, 3 and 5.
choose rolls dice with random from part 6, which gives the same number whenever it is asked with the same time and seed. The time it gets here is not the beginning of the stretch but a fixed point of the cycle, its middle: cycle + 0.5. That is the same for every piece of the cycle, so the pick holds however the cycle is cut into stretches, and it is the same again when the cycle is asked for a second time.
Both hand the picked pattern only the piece of the stretch that lies inside its cycle. Every event still comes back exactly once.
New symbols
The notation needs four new symbols: {, }, | and %. In src/mini.ts, replace the SYMBOLS of the tokenizer:
const SYMBOLS = '[]<>(){},|~*/@_!?%';The tree gets two new kinds of nodes, choice and polymeter, and fast and slow hold a list of factors instead of a single one. Replace the Node type:
export type Node =
| { type: 'atom'; value: Atom }
| { type: 'rest' }
| { type: 'sequence'; steps: Step[] }
| { type: 'stack'; layers: Node[] }
| { type: 'alternate'; steps: Step[] }
| { type: 'choice'; options: Node[]; seed: number }
| { type: 'polymeter'; layers: Node[]; steps: number | undefined }
| { type: 'fast'; node: Node; factors: number[] }
| { type: 'slow'; node: Node; factors: number[] }
| { type: 'sometimes'; node: Node; amount: number; seed: number }
| { type: 'euclid'; node: Node; pulses: number; steps: number; rotation: number };The compiler is going to call choose and takeTurns. Replace the import at the top of the file:
import {
choose,
euclid,
fast,
pure,
sequence,
silence,
slow,
sometimes,
stack,
takeTurns,
type Pattern,
} from './pattern.ts';Choices: a | b
bd*2 | bd*4 plays one of its two sides for a whole cycle and decides again in the next. That is different from ?, which drops single events: | chooses between whole sequences, and there can be more than two, as in bd sd | bd bd sd | bd(3,8).
In the grammar, | stands where , stands: between sequences. So the rule for layers reads both, and the separator decides what the group becomes. Replace parseLayers():
/** layers = sequence ("," sequence)* | sequence ("|" sequence)* */
private parseLayers(): Node {
const layers = [this.parseSequence()];
let separator: string | undefined;
while (this.isSymbol(',') || this.isSymbol('|')) {
const token = this.next();
if (separator && separator !== token.text) {
throw new MiniError('"," and "|" can\'t be mixed in one group', token.start);
}
separator = token.text;
layers.push(this.parseSequence());
}
if (layers.length === 1) return layers[0];
if (separator === ',') return { type: 'stack', layers };
const seed = this.seed;
this.seed += 1;
return { type: 'choice', options: layers, seed };
}A group is either layers or a choice. bd, sd | cp could be read in two ways, so it is a mistake, reported at the second separator. Brackets say which reading is meant: bd, [sd | cp].
Each choice takes a seed from the counter that ? already uses. Two choices in one pattern then roll different dice and don't always pick alike. Change the comment above the counter in the Parser class to say so:
/** Counts up, so that every "?" and "|" in a pattern rolls dice of its own. */
private seed = 0;A sequence has to end when it reaches a |, and at the } of the next section. Replace atSequenceEnd():
private atSequenceEnd(): boolean {
const token = this.peek();
return token.type === 'end' || (token.type === 'symbol' && ']>},|)'.includes(token.text));
}In compile(), add a case after 'alternate':
case 'choice':
return choose(node.options.map(compile), node.seed);"Per cycle" means a cycle of the choice's own time. In ~ [sd | cp] the group fills the second half of every cycle, and the choice is made once per cycle. In [sd | cp]*2 the group runs twice per cycle, and each run picks for itself.
Polymeter: {a b c}%4
In brackets, layers share the cycle. In [bd hh sd hh, cb ~ ~] the four steps of the first layer and the three steps of the second both fill one cycle, so the steps of the second layer are longer. Curly braces turn that around. In {bd hh sd hh, cb ~ ~} every step of every layer has the same length, and the layers differ in length instead. The first layer sets the pace: it has four steps, so four steps fill a cycle. The second layer has three. It is over after three quarters of the cycle and starts again right there. This is a polymeter: several meters, here one of four steps and one of three, running at the same time. A meter is the number of steps after which a figure starts over.
Written with an x for a hit and a dot for a step without one, three cycles of four steps look like this. The lines only mark where a cycle ends:
x...|x...|x...is thebdof the first layer, at the start of every cycle.x..x|..x.|.x..is thecbof the second layer, on every third step.
The cowbell lands on a different step in each cycle: it drifts against the beat. After twelve steps, which is three cycles, both layers begin together again and the figure repeats.
A number after % sets the pace in place of the first layer. {hh hh oh}%8 plays eight steps per cycle from a layer of three. The open hi-hat falls on steps 3 and 6 in the first cycle, on 1, 4 and 7 in the second, and on 2, 5 and 8 in the third.
The braces are a new kind of step. Replace parseStep():
/** step = word | "~" | "[" layers "]" | "<" layers ">" | "{" layers "}" ("%" n)? */
private parseStep(): Node {
const token = this.next();
if (token.type === 'word') {
const number = Number(token.text);
return { type: 'atom', value: Number.isFinite(number) ? number : token.text };
}
if (token.text === '~') return { type: 'rest' };
if (token.text === '[') {
const inner = this.parseLayers();
this.expect(']');
return inner;
}
if (token.text === '<') {
const inner = this.parseLayers();
this.expect('>');
return alternate(inner);
}
if (token.text === '{') {
const inner = this.parseLayers();
this.expect('}');
let steps: number | undefined;
if (this.isSymbol('%')) {
this.next();
steps = this.parseNumber();
}
return { type: 'polymeter', layers: inner.type === 'stack' ? inner.layers : [inner], steps };
}
throw new MiniError(
token.type === 'end' ? 'The pattern ends too early' : `Unexpected "${token.text}"`,
token.start,
);
}Inside the braces the same rule applies as inside brackets: parseLayers(). If it comes back with a stack, the layers of the stack are the layers of the polymeter. Anything else is a single layer. In compile(), add the case after 'choice':
case 'polymeter': {
// Every layer runs at the same speed: `steps` of its steps per cycle.
const counts = node.layers.map((layer) => stepsOf(layer).reduce((sum, step) => sum + step.repeat, 0));
const steps = node.steps ?? counts[0] ?? 1;
return stack(
node.layers.map((layer, index) =>
counts[index] ? fast(steps / counts[index], compileSteps(stepsOf(layer))) : silence(),
),
);
}No new pattern function is needed. Each layer is compiled as a sequence that fills one cycle, and fast gives it its speed: a layer of three steps that should play four steps per cycle runs 4/3 times as fast. A step that is repeated with ! counts as often as it is played.
Changing speeds: hh*<2 4>
hh*2 plays two hi-hats per cycle, hh*4 four. hh*<2 4> takes turns: two in one cycle, four in the next. The angle brackets mean what they mean around steps, one per cycle, but here they hold numbers. Add a method to the parser, below parseNumber():
/** factor = n | "<" n+ ">": one speed, or one per cycle, taking turns */
private parseFactors(): number[] {
if (!this.isSymbol('<')) return [this.parseNumber()];
const open = this.next();
const factors: number[] = [];
while (!this.isSymbol('>')) {
if (this.peek().type === 'end') throw new MiniError('Missing ">"', open.start);
factors.push(this.parseNumber());
}
this.next();
if (factors.length === 0) throw new MiniError('"<>" needs a number', open.start);
return factors;
}A single number comes back as a list of one. In parseModifiers(), replace the cases of * and /:
case '*':
this.next();
step.node = { type: 'fast', node: step.node, factors: this.parseFactors() };
break;
case '/':
this.next();
step.node = { type: 'slow', node: step.node, factors: this.parseFactors() };
break;The comment above parseModifiers() states the rule. Change it to:
/** modifier = "*" factor | "/" factor | "@" n | "!" n? | "?" n? | "(" n "," n ("," n)? ")" */In compile(), replace the cases 'fast' and 'slow':
case 'fast': {
const inner = compile(node.node);
return takeTurns(node.factors.map((factor) => fast(factor, inner)));
}
case 'slow': {
const inner = compile(node.node);
return takeTurns(node.factors.map((factor) => slow(factor, inner)));
}The step is compiled once, and takeTurns gets it at each of the speeds. With a single factor, takeTurns gives back that one pattern, so hh*4 works as it did.
The input of the page should start with a pattern that uses the new notation. In index.html, replace the <input>. In HTML, the angle brackets of the pattern are written as < and >:
<input id="pattern" value="bd*<2 4>, ~ [sd | cp], {hh hh oh}%8" spellcheck="false" autocomplete="off" />The whole notation
The language is complete. Here is every symbol of parts 5 to 7, each with a pattern to type in:
bd sd: steps, separated by spaces, share the cycle evenly. A step is a word, such as the name of a sound, or a number. Example:bd sd hh sd~: a rest, a step without a sound. Example:bd ~ sd ~[a b]: a group, a sequence in the room of one step. Example:bd [sd sd]a, b: layers, sequences that play at the same time and each fill the cycle or the group. Example:bd sd, hh hh hh<a b>: one of the steps per cycle, taking turns. Example:bd <sd cp>a*n: faster, the step plays n times in its room. Example:hh*4a/n: slower, the step takes n times as long. Example:bd/2, a kick in every second cyclea@n: a weight, the step gets n times the room of a plain step. Example:bd@3 sda _: makes the step before it one step longer. Example:bd _ _ sd, the same asbd@3 sda!anda!n: plays the step once more, or n times in all. Example:bd!3 sd, the same asbd bd bd sda?anda?n: drops each event with a chance of a half, or of n. Example:hh*8?0.2a(3,8): a euclidean rhythm, 3 hits spread as evenly as possible over 8 steps. A third number rotates it by that many steps. Example:bd(3,8),bd(3,8,2)a | b: one of the sequences per cycle, picked by chance. It can't be mixed with,in the same group. Example:bd*2 | bd*4{a b c, d e}: a polymeter, layers whose steps all have the same length, as many per cycle as the first layer has. Example:{bd hh sd hh, cb ~ ~}{a b c}%n: a polymeter with n steps per cycle. Example:{hh hh oh}%8a*<2 4>anda/<2 4>: a speed per cycle, taking turns. Example:hh*<2 4>
Modifiers come after their step and can follow one another: [bd sd]*2, hh*8?0.2, bd(3,8)?.
Try it
Press Play. The demo starts with bd*<2 4>, ~ [sd | cp], {hh hh oh}%8. The kick plays twice in one bar and four times in the next. In the middle of every bar comes either a snare or a clap. The dice of this pattern fall the same way after every Play: the snare in the first four bars, the first clap in bar 5. The open hi-hat is on a different step in every bar and comes around after three.
Type
{bd hh sd hh, cb ~ ~}and follow the cowbell: when it falls on the first step of a bar, it is back there three bars later.Change
{hh hh oh}%8to{hh hh oh}%6. The drift is gone, because six steps are exactly two rounds of the three.Type
hh*<4 8 16>: the hi-hat doubles its speed twice, then starts over.Type
bd sd | bd bd sd | bd(3,8): each bar is one of the three, and nothing tells you which comes next.Type
bd, sd | cp. The message under the input points at the|, and the last good pattern plays on.
The drums have a language now, but they are the only instrument. The next part builds a synth, and the same notation plays notes on it.
Comments
The comments are GitHub Discussions: sign in with GitHub to write one.
The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.