Reference notebook

Download .ipynb Open in the browser

“Open in the browser” runs the notebook on your computer with JupyterLite: no installation, no account. Your changes stay in that browser: download the notebook to keep them.

From sounds to a rhythmic language

Lesson 04 · ACTAM 2026

We have a small drum kit. How can we describe a rhythm without writing out every sample?

We will start by placing sounds in time, then invent a small notation for hits and rests. A pattern will become a track; several tracks will become a piece. Our functions still return ordinary lists of samples.

How to use this notebook

Run the cells from top to bottom. At each Your turn, predict or try before reading the worked example. Click the players to listen, starting at a low volume. Playback is only a renderer; automatic normalisation and autoplay are disabled.

Recall: lists, slicing, repetition, comprehensions, functions, loops, tuples, zip, conditionals and mixing come from lessons01–03. We explain string notation locally, so the text workshop is not a prerequisite.

New or made explicit here: passing a function as an argument, describing tracks as data, and reading a small pattern language. Functions stored as values appeared in the live lesson03 draft; the refined lesson03 notebook did not develop them. We will revisit that idea step by step.

The final sections are optional: a character-to-function dictionary, a compact mixer, and ten listening challenges. You do not need to finish them all in one session.

1. Bring back the kit

This is the kit from lesson03: sources, envelopes, a VCA, a two-input mixer and four instruments. Run the following cell; there is no need to rebuild the instruments today.

Keep one distinction in mind: mix(a, b, ga, gb) adds equally long signals with independent gains. We will keep that function unchanged and give the future multitrack mixer a different name.

The square-wave source is still a simple, non-band-limited model. These are sound-design recipes, not complete physical models.

SR = 48000

from math import exp
from random import random

def vca(wave, signal):
    if len(wave) != len(signal):
        raise ValueError("The sound and control signal must have equal lengths.")
    return [x * gain for x, gain in zip(wave, signal)]

def noise(duration=0.05, amplitude=0.15, sample_rate=SR):
    n = round(duration * sample_rate)
    return [amplitude * (2 * random() - 1) for _ in range(n)]

def envelope_lin(duration=0.05, sample_rate=SR):
    n = round(duration * sample_rate)
    denominator = max(1, n - 1)
    return [1 - i / denominator for i in range(n)]

def square_wave_f(f, sample_rate=SR, amplitude=0.15):
    phase = 0.0
    wave = []
    for frequency in f:
        if not 0 < frequency < sample_rate / 2:
            raise ValueError("Each frequency must be positive and below half the sample rate.")
        wave.append(-amplitude if phase < 0.5 else amplitude)
        phase = (phase + frequency / sample_rate) % 1
    return wave

def edge_fade(wave, attack=0.001, release=0.005, sample_rate=SR):
    n = len(wave)
    attack_samples = max(1, round(attack * sample_rate))
    release_samples = max(1, round(release * sample_rate))
    edge = [
        min(1.0, i / attack_samples, (n - 1 - i) / release_samples)
        for i in range(n)
    ]
    return vca(wave, edge)

def envelope_exp(duration=0.05, tau=0.012, sample_rate=SR):
    if tau <= 0:
        raise ValueError("tau must be positive.")
    n = round(duration * sample_rate)
    return [exp(-(i / sample_rate) / tau) for i in range(n)]

def closed_hat(duration=0.06, tau=0.010, amplitude=0.15, sample_rate=SR):
    source = noise(duration, amplitude=amplitude, sample_rate=sample_rate)
    shape = envelope_exp(duration, tau=tau, sample_rate=sample_rate)
    return edge_fade(vca(source, shape), sample_rate=sample_rate)

def open_hat(duration=0.30, tau=0.070, amplitude=0.15, sample_rate=SR):
    source = noise(duration, amplitude=amplitude, sample_rate=sample_rate)
    shape = envelope_exp(duration, tau=tau, sample_rate=sample_rate)
    return edge_fade(vca(source, shape), sample_rate=sample_rate)

def kick_raw(
    duration=0.25, start_hz=180, end_hz=45,
    pitch_tau=0.025, amp_tau=0.060,
    amplitude=0.20, sample_rate=SR,
):
    pitch_shape = envelope_exp(duration, tau=pitch_tau, sample_rate=sample_rate)
    pitch = [end_hz + (start_hz - end_hz) * value for value in pitch_shape]
    body = square_wave_f(pitch, sample_rate=sample_rate, amplitude=amplitude)
    shape = envelope_exp(duration, tau=amp_tau, sample_rate=sample_rate)
    return vca(body, shape)

def kick(
    duration=0.25, start_hz=180, end_hz=45,
    pitch_tau=0.025, amp_tau=0.060,
    amplitude=0.20, sample_rate=SR,
):
    wave = kick_raw(
        duration=duration, start_hz=start_hz, end_hz=end_hz,
        pitch_tau=pitch_tau, amp_tau=amp_tau,
        amplitude=amplitude, sample_rate=sample_rate,
    )
    return edge_fade(wave, sample_rate=sample_rate)

def mix(a, b, ga=1.0, gb=1.0):
    if len(a) != len(b):
        raise ValueError("Pad the shorter sound with silence before mixing.")
    return [ga * x + gb * y for x, y in zip(a, b)]

def snare(
    duration=0.20, amplitude=0.15, noise_gain=0.5,
    sample_rate=SR,
):
    pitch = [
        180 + 120 * value
        for value in envelope_exp(duration, tau=0.010, sample_rate=sample_rate)
    ]
    body = vca(
        square_wave_f(pitch, amplitude=amplitude, sample_rate=sample_rate),
        envelope_exp(duration, tau=0.025, sample_rate=sample_rate),
    )
    wires = vca(
        noise(duration, amplitude=amplitude, sample_rate=sample_rate),
        envelope_exp(duration, tau=0.055, sample_rate=sample_rate),
    )
    return edge_fade(
        mix(body, wires, ga=1.0, gb=noise_gain),
        sample_rate=sample_rate,
    )
from IPython.display import Audio

def play(wave, sample_rate=SR):
    return Audio(wave, rate=sample_rate, normalize=False, autoplay=False)

play(snare())

Your turn · A control we already know

Reuse the same body/noise balance idea from lesson03. Compare snare(noise_gain=0) with snare(noise_gain=1).

The first removes the noisy wires, not the pitched body. Repeated calls generate fresh noise, so the exact samples also vary. All generators and renderers must agree on the sample rate; a plain sample list does not store it.

2. Give a sound a slot

A slot is the amount of time reserved for a hit or a rest. For now, a sound that is too long will be cut; one that is too short will be followed by silence. Preserving overlapping tails will need a different scheduler.

Recall: a slice keeps part of a list, + concatenates lists, and [0] * n makes silence. We use max to make the amount of padding explicitly nonnegative.

Use a nonnegative integer number of samples. For these inputs, the helper returns a new list of exactly that length; we state the assumption rather than checking it in the function.

def fit(wave, n_samples):
    padding = max(0, n_samples - len(wave))
    return wave[:n_samples] + [0] * padding

print(fit([1, 2, 3], 5))
print(fit([1, 2, 3], 2))
print(fit([], 4))

Your turn · Predict before listening

What will fit([1, 2, 3], 0) return? What is the difference between [] and fit([], 4)?

An empty list occupies no time. Four zero samples occupy four sample periods. Cutting a sound can introduce an abrupt boundary; our slot model is intentionally simple.

3. From tempo to sample counts

Here one beat is a quarter note. At 100 beats per minute, a beat lasts 60 / 100 seconds. An eighth note lasts half as long, and a sixteenth lasts a quarter as long.

We will call the duration of one pattern character step_s, not beat_s: a step may represent an eighth, a sixteenth, or another subdivision.

Round a duration in seconds times the sample rate to obtain an integer number of samples. Repeating rounded slots can introduce a tiny timing error; we use one consistent slot size throughout a pattern.

bpm = 100
quarter_s = 60 / bpm
eighth_s = quarter_s / 2
step_s = quarter_s / 4
step_samples = round(step_s * SR)

print(quarter_s, eighth_s, step_s)
print(step_samples)
one_hat = fit(closed_hat(), round(quarter_s * SR))
four_hats = one_hat * 4
play(four_hats)

Your turn · Same hit or another hit?

one_hat * 4 repeats exactly the same sample buffer. Calling closed_hat() four times produces four fresh noise realisations.

Try the following version. Both have the same timing; what is reused in each case?

fresh_hats = []
for i in range(4):
    fresh_hats = fresh_hats + fit(closed_hat(), round(quarter_s * SR))

play(fresh_hats)

4. After each other, or together?

Build a four-beat kick part using hits and rests. Build an eight-note hat part over the same duration.

List + places signals after each other. Our mix adds their samples at the same time. Predict the lengths before listening.

quarter_samples = round(quarter_s * SR)
eighth_samples = round(eighth_s * SR)

kick_slot = fit(kick(), quarter_samples)
rest_slot = fit([], quarter_samples)
kicks = kick_slot + rest_slot + kick_slot + rest_slot
hats = fit(closed_hat(), eighth_samples) * 8

print(len(kicks), len(hats))
print(len(kicks + hats), len(mix(kicks, hats)))
play(mix(kicks, hats, ga=1.0, gb=0.7))

Your turn · Change one relationship

Move the second kick to the fourth beat. Then make the hats quieter without changing their timing.

At this tempo the rounded eighth-note and quarter-note lengths line up exactly. At other tempos, separately rounding different subdivisions need not give equal totals. A shared smallest step avoids that mismatch.

5. Join a list of slots

Reuse sum(parts, []) from lesson02 to place sample lists one after another.

Recall: the empty list is the starting value. This behaves like [] + parts[0] + parts[1] + ...: concatenation, not simultaneous mixing.

parts = [[1, 2], [], [3], [4, 5]]
print(sum(parts, []))
parts = [kick(), [], kick(), []]
slots = [fit(part, quarter_samples) for part in parts]
play(sum(slots, []))

Without [], sum starts from 0, which cannot be added to a list. As in lesson02, repeated list addition is convenient for short examples but copies data; it is not an efficient long-track engine.

6. A function is also a value

We have called kick() many times. What does kick, without parentheses, mean?

  • kick refers to the function: a recipe we can use later.
  • kick() calls that function now and returns samples.
  • Assigning instrument = kick gives another name to the same function. It does not generate a sound.

The live lesson03 draft stored functions inside a kit. Here we make the mechanism explicit before using it in a pattern reader.

instrument = kick
wave = instrument(sample_rate=SR)
print(len(wave))
play(wave)

Pass the recipe to another function

A parameter can receive a function just as it can receive a number or a list. Inside make_hit, the name instrument refers to whichever function the caller supplied.

Our instrument contract is small: accept sample_rate=... and return a list of samples at that rate. The kit already does this.

def make_hit(instrument, sample_rate=SR):
    return instrument(sample_rate=sample_rate)

play(make_hit(closed_hat))

Your turn · Locate the call

Change closed_hat to snare. Point to the parentheses that actually generate the sound.

Why is make_hit(kick()) different? It would pass a sample list, then try to call that list as a function. Pass kick when the receiving function needs a recipe.

7. A tiny language for hits and rests

Let "x" mean “make a hit” and "." mean “leave a silent step”. For example, "x.x." has four steps and two hits.

Text reminder: quotes make a string; a loop visits its characters in order; len(pattern) counts them; multiplying a string repeats it. The quotes themselves are not part of the pattern.

Before generating audio, translate each symbol into a small decision: 1 for a hit, 0 for a rest. We call this read_pattern, rather than a generic parse, because its accepted language is deliberately narrow.

Recall · Conditions and errors

== compares values; = assigns a value. An if statement executes its indented body when the comparison is true.

New spelling: elif means “otherwise, if”. It tests another condition only when the earlier one failed. else handles the remaining case. raise ValueError(...) reports an invalid input and stops the call.

The tempting rule “anything except x is silence” would hide typing mistakes. We accept exactly x and .; spaces, uppercase letters and other symbols are errors.

def read_pattern(pattern):
    steps = []
    for symbol in pattern:
        if symbol == "x":
            steps.append(1)
        elif symbol == ".":
            steps.append(0)
        else:
            raise ValueError("Use only x for a hit and . for a rest.")
    return steps

print(read_pattern("x.x."))
print(read_pattern("x." * 4))

Your turn · Read without sound

Predict the result of read_pattern(".xx..."). How many steps? How many hits?

In a separate scratch cell, try read_pattern("x X."). Read the error, then fix the input. What should an empty pattern produce?

We validate the complete text before generating any audio, so a typo cannot leave us with a partly rendered result.

8. Turn decisions into samples

The reader answers what happens at each step. The renderer answers how that becomes sound.

For each decision, generate a fresh hit or an empty buffer, fit it to one step, and concatenate the slots. The same sample rate is passed to the instrument and used to calculate the slot length.

For all the renderers below, use positive sample rates and step durations yielding at least one sample after rounding. We state these assumptions rather than checking them repeatedly. Checks for matching signal lengths and recognised pattern symbols remain because they explain the model.

def render_pattern(pattern, instrument, step_s, sample_rate=SR):
    n = round(step_s * sample_rate)

    steps = read_pattern(pattern)
    slots = []
    for hit in steps:
        if hit == 1:
            wave = instrument(sample_rate=sample_rate)
        else:
            wave = []
        slots.append(fit(wave, n))
    return sum(slots, [])

play(render_pattern("x.x.x.x.", closed_hat, eighth_s))

Your turn · One description, several interpretations

  1. Keep the pattern but switch instrument.
  2. Keep the instrument but halve step_s.
  3. Change just one character.
  4. Predict the sample count before calling len.

Each valid pattern produces len(pattern) * round(step_s * sample_rate) samples, even if every character is a rest. An empty pattern produces []; there is nothing to send to a player.

pattern = "x...x...x...x..."
wave = render_pattern(pattern, kick, step_s)
print(len(wave), len(pattern) * round(step_s * SR))
play(wave)

The sample rate must travel all the way

Changing the rate only for padding would put incorrectly generated samples on a new time scale. Use the same value for synthesis, scheduling and playback.

rate = 24000
wave_at_24k = render_pattern("x.x.", closed_hat, step_s, sample_rate=rate)
play(wave_at_24k, sample_rate=rate)

9. A separate mixer for many tracks

Keep mix(a, b, ga, gb) for two signals and their gain controls. In particular, snare still uses it for its body and wires.

Our new mix_tracks(waves) takes a list of sample lists, pads shorter tracks with silence, and adds them. Padding extends a track; it does not repeat it.

Python looks up global function names when a function runs. Redefining mix would therefore also change what snare calls. Different names let both contracts coexist.

def mix_tracks(waves):
    if len(waves) == 0:
        return []
    longest = max([len(wave) for wave in waves])
    result = [0] * longest
    for wave in waves:
        result = mix(result, fit(wave, longest))
    return result

print(mix_tracks([[1, 2], [10], []]))
print(mix_tracks([]))
kicks = render_pattern("x...x...x...x...", kick, step_s)
snares = render_pattern("....x.......x...", snare, step_s)
hats = render_pattern("x.x.x.x.x.x.x.x.", closed_hat, step_s)
play(mix_tracks([kicks, snares, hats]))

Your turn · Ending and balance

Shorten the hat pattern. Does the mixer repeat the hats, truncate the other parts, or add silence?

To change a whole track's gain, scale its samples before mixing: [0.5 * x for x in hats]. This uses the multiplication and comprehension we already know. Try it.

Adding tracks can push samples outside −1 to +1. Keep source amplitudes and gains moderate. The player does not normalise the result, so gain changes remain meaningful.

10. Describe a track as data

A track needs a pattern, an instrument and a step duration. Store those three values in a tuple.

Recall: tuples group related values; unpacking assigns each component to a name. Here one component happens to be a function. The three tracks below use the same step duration, but they need not have the same number of steps.

kick_track = ("x...x...x...x...", kick, step_s)
snare_track = ("....x.......x...", snare, step_s)
hat_track = ("x.x.x.x.x.x.x.x.", closed_hat, step_s)

def render_track(track, sample_rate=SR):
    pattern, instrument, step_s = track
    return render_pattern(pattern, instrument, step_s, sample_rate=sample_rate)

def render_tracks(tracks, sample_rate=SR):
    waves = [render_track(track, sample_rate=sample_rate) for track in tracks]
    return mix_tracks(waves)

tracks = [kick_track, snare_track, hat_track]
play(render_tracks(tracks))

Your turn · Write a small piece

Build a one-bar rhythm on 16 sixteenth-note steps. Include a rest, a simultaneous hit, and one change in the second bar.

Keep the musical description separate from the rendering call. Exchange track data with a neighbour: can they explain the rhythm without running the instrument definitions?

Then render at 24,000 Hz and play at that same rate. Which parts of your musical description need to change?

11. Extend the language: accents

So far every hit on a track has the same scale. We want x for an ordinary hit, X for an accent, and . for a rest.

Before reading the worked example, propose two changes:

  1. What should the reader return instead of only 0 and 1?
  2. Where should the renderer apply that value?

Choose 0.5 for an ordinary hit and 1.0 for an accent. These are relative sample gains, not a model of perceived loudness. Keeping the largest gain at 1 leaves more room for the mix.

Worked example · Read gains, then apply them

We give the extended reader and renderer new names so the earlier two-symbol language remains available. if gain > 0 decides whether to call the instrument; multiplying the generated samples applies the requested gain.

def read_accents(pattern):
    gains = []
    for symbol in pattern:
        if symbol == "x":
            gains.append(0.5)
        elif symbol == "X":
            gains.append(1.0)
        elif symbol == ".":
            gains.append(0.0)
        else:
            raise ValueError("Use only x, X and . in an accented pattern.")
    return gains

def render_accents(pattern, instrument, step_s, sample_rate=SR):
    n = round(step_s * sample_rate)

    gains = read_accents(pattern)
    slots = []
    for gain in gains:
        if gain > 0:
            hit = instrument(sample_rate=sample_rate)
            wave = [gain * sample for sample in hit]
        else:
            wave = []
        slots.append(fit(wave, n))
    return sum(slots, [])

print(read_accents("X.x."))
play(render_accents("XxxxXxxxXxxxXxxx", closed_hat, step_s))

Your turn · Let accents become track data

Make a quiet snare ghost note before a stronger hit. Then adapt the track renderer to use render_accents.

Keep the original renderer working: give your new version a descriptive name. Can two patterns with identical hit positions suggest different phrasing just through accents?

Notice that redefining a function is allowed, but callers using its global name will use the latest definition. Deliberate names make notebook state easier to reason about.

What have we built?

The pattern is a description, the reader gives its symbols meaning, and the renderer turns those meanings into samples.

We still have the same three operations:

  • concatenation places sounds in time;
  • multiplication scales their samples;
  • mixing adds simultaneous signals.

The new power comes from organising those operations, not from changing the audio representation. Keep one rhythm, an accented variation, and a short explanation of where text becomes decisions and where decisions become sound.

The remaining sections are optional extensions and listening practice.

Optional A · Choose instruments with a dictionary

What if k meant kick, s meant snare and h meant closed hat?

New tool: a dictionary. It associates keys with values. In {"k": kick}, "k" is a key and kick is its value. Unlike list indexing by position, kit["k"] looks up a value by key. That value is a function; adding parentheses calls it.

This notation appeared in the live lesson03 draft. We explain it here so it is not a hidden prerequisite.

kit = {"k": kick, "s": snare, "h": closed_hat, "o": open_hat}
instrument = kit["k"]
play(instrument(sample_rate=SR))

Validate before looking up

New use of membership: symbol in kit asks whether a dictionary contains that key. not in asks the opposite. and requires both conditions to be true.

We reserve . for silence, outside the dictionary. Any other symbol must be a key. First validate the entire pattern; only then generate sound. Multiple instruments in one string still occur in successive slots: use separate tracks for simultaneous hits.

def render_kit(pattern, kit, step_s, sample_rate=SR):
    n = round(step_s * sample_rate)

    for symbol in pattern:
        if symbol != "." and symbol not in kit:
            raise ValueError("A pattern symbol is missing from the kit.")

    slots = []
    for symbol in pattern:
        if symbol == ".":
            wave = []
        else:
            instrument = kit[symbol]
            wave = instrument(sample_rate=sample_rate)
        slots.append(fit(wave, n))
    return sum(slots, [])

play(render_kit("k.h.s.h.k.h.s.o.", kit, step_s))

Your turn · Change the interpretation

Create another dictionary with the same keys but different instruments. Render the same string with it.

To customise an instrument, use a named wrapper with the same sample-rate contract. The short form lambda would create an anonymous function, but we do not need it: a normal def makes the parameters and returned value visible.

def soft_snare(sample_rate=SR):
    return snare(amplitude=0.07, noise_gain=0.3, sample_rate=sample_rate)

soft_kit = {"k": kick, "s": soft_snare, "h": closed_hat, "o": open_hat}
play(render_kit("k.h.s.h.k.h.s.o.", soft_kit, step_s))

Optional B · Read a compact mixer

The main lesson does not require this version. First recall zip: it groups corresponding positions. With more than two inputs, each group contains more than two values.

New: two uses of *.

  • In def mix_many(*waves), it collects positional arguments into a tuple named waves.
  • In zip(*padded), it expands a collection into separate positional arguments.

These are not list repetition: the meaning depends on where * appears. We use a list comprehension, not a generator expression, to avoid introducing another construct at the same time.

a = [1, 2]
b = [10, 20]
c = [100, 200]
padded = [a, b, c]
print(list(zip(a, b, c)))
print(list(zip(*padded)))
def mix_many(*waves):
    if len(waves) == 0:
        return []
    longest = max([len(wave) for wave in waves])
    padded = [fit(wave, longest) for wave in waves]
    columns = zip(*padded)
    return [sum(column) for column in columns]

print(mix_many(a, b, c))
print(mix_tracks([a, b, c]))

Your turn · Explain the compact form

Compare the call mix_many(a, b, c) with mix_tracks([a, b, c]). Then explain what one column represents.

The numerical sum here mixes one simultaneous sample from each track. It is not the list concatenation shortcut discussed earlier. Both mixers preserve the longest input and add silence to shorter ones; neither replaces the gain-controlled mix used by the snare.

Optional C · Listening laboratory

Ten challenges expressed in our pattern language. Listen, sketch the onsets on a grid, then reconstruct the tracks before revealing the recipe.

Each track contains a pattern, an instrument and a step duration. Most challenges use sixteenths; one uses thirds of a beat and another thirty-seconds. Accents use x and X. The last challenge extends the renderer to alternate long and short steps.

These versions preserve the original onset patterns. They are not sample-identical recreations: the renderer makes fresh hits and cuts each sound to its step, so some tails are shorter than in the manually fitted draft. The accent challenge uses our standard 0.5/1.0 gains rather than the draft's individual amplitudes. Repeating the rendered bar then repeats that exact buffer.

The source cells are marked hidden/collapsed for interfaces that support this metadata. Run a cell to create its player, then hide its code for listening. The code remains in the downloadable file; an audio-only quiz page is a separate publication step. Playback is unnormalised and never automatic.

Listening challenge 1 · Four beats and the spaces between

Listen before expanding the code. Mark each instrument's attacks and identify the step duration.

bpm = 120
step_s = 60 / bpm / 4

tracks = [
    ("x...x...x...x...", kick, step_s),
    ("..x...x...x...x.", closed_hat, step_s),
]
phrase = render_tracks(tracks)
play(phrase * 4)

Listening challenge 2 · A second kick before the next beat

Listen before expanding the code. Mark each instrument's attacks and identify the step duration.

bpm = 110
step_s = 60 / bpm / 4

tracks = [
    ("x.......x.x.....", kick, step_s),
    ("....x.......x...", snare, step_s),
    ("x.x.x.x.x.x.x.x.", closed_hat, step_s),
]
phrase = render_tracks(tracks)
play(phrase * 4)

Listening challenge 3 · Open and closed hats

Listen before expanding the code. Mark each instrument's attacks and identify the step duration.

bpm = 124
step_s = 60 / bpm / 4

tracks = [
    ("x...x...x...x...", kick, step_s),
    ("....x.......x...", snare, step_s),
    ("x.x.x.x.x.x.x.x.", closed_hat, step_s),
    ("..x...x...x...x.", open_hat, step_s),
]
phrase = render_tracks(tracks)
play(phrase * 4)

Listening challenge 4 · An off-grid-looking kick

Listen before expanding the code. Mark each instrument's attacks and identify the step duration.

bpm = 90
step_s = 60 / bpm / 4

tracks = [
    ("x......x..x.....", kick, step_s),
    ("....x.......x...", snare, step_s),
    ("x.x.x.x.x.x.x.x.", closed_hat, step_s),
]
phrase = render_tracks(tracks)
play(phrase * 4)

Listening challenge 5 · A displaced snare phrase

Listen before expanding the code. Mark each instrument's attacks and identify the step duration.

bpm = 95
step_s = 60 / bpm / 4

tracks = [
    ("x...x...x...x...", kick, step_s),
    ("...x..x....x..x.", snare, step_s),
    ("x.x.x.x.x.x.x.x.", closed_hat, step_s),
]
phrase = render_tracks(tracks)
play(phrase * 4)

Listening challenge 6 · A three-part beat

Listen before expanding the code. Mark each instrument's attacks and identify the step duration. Three steps fit into one beat; this is not a sixteenth-note grid.

bpm = 100
step_s = 60 / bpm / 3

tracks = [
    ("x.....x.x...", kick, step_s),
    ("...x.....x..", snare, step_s),
    ("x.xx.xx.xx.x", closed_hat, step_s),
]
phrase = render_tracks(tracks)
play(phrase * 4)

Listening challenge 7 · Ghost notes and accents

Listen before expanding the code. Mark each instrument's attacks and identify the step duration.

This solution uses render_accent_tracks: unpack each track, call the existing render_accents, then mix the resulting waves. This is the adaptation proposed in section 11, using only familiar loops and unpacking. X is full gain and x is half gain. Compare hit positions separately from their strength.

def render_accent_tracks(tracks, sample_rate=SR):
    waves = []
    for pattern, instrument, step_s in tracks:
        wave = render_accents(pattern, instrument, step_s, sample_rate=sample_rate)
        waves.append(wave)
    return mix_tracks(waves)

bpm = 100
step_s = 60 / bpm / 4

tracks = [
    ("X.....x...X.....", kick, step_s),
    ("..x.X.xx.x..X..x", snare, step_s),
    ("x.x.X.x.x.x.X.x.", closed_hat, step_s),
]
phrase = render_accent_tracks(tracks)
play(phrase * 4)

Listening challenge 8 · A two-bar phrase

Listen before expanding the code. Mark each instrument's attacks and identify the step duration.

bpm = 136
step_s = 60 / bpm / 4

tracks = [
    ("x.x.......xx....x.x.......x.....", kick, step_s),
    ("....x..x.x..x..x....x..x.x....x.", snare, step_s),
    ("x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.", closed_hat, step_s),
]
phrase = render_tracks(tracks)
play(phrase * 2)

Listening challenge 9 · A faster hat ending

Listen before expanding the code. Mark each instrument's attacks and identify the step duration.

bpm = 140
step_s = 60 / bpm / 8

tracks = [
    ("x.............x...........x.....", kick, step_s),
    ("................x...............", snare, step_s),
    ("x.x.x.x.x.x.x.x.x.x.x.x.xxxxx.x.", closed_hat, step_s),
]
phrase = render_tracks(tracks)
play(phrase * 4)

Listening challenge 10 · Long and short subdivisions

The final rhythm alternates long and short sixteenths. Our constant-step renderer cannot express this directly.

Your turn: keep the hit/rest pattern, but propose a second list that describes the duration of each step. What must have the same length? How can zip pair each decision with its duration?

The worked extension below uses sample counts, so every track shares exactly the same boundaries. A pair has 2 * s samples: calculate the long part, then obtain the short part by subtraction. The pair keeps its total duration despite rounding.

render_timed_pattern pairs decisions and lengths, generates each hit and fits it to its assigned slot. A length check prevents zip from silently dropping steps. render_timed_tracks applies this to the familiar track tuples, whose third value is now the list of slot lengths. Use positive integer lengths and the same sample rate for instruments, timing and playback.

This is a new rendering rule, not a new meaning for x or .. Compare it with the same patterns rendered with equal slots.

def render_timed_pattern(pattern, instrument, step_lengths, sample_rate=SR):
    steps = read_pattern(pattern)
    if len(steps) != len(step_lengths):
        raise ValueError("Give each pattern step one slot length.")
    slots = []
    for hit, n in zip(steps, step_lengths):
        if hit == 1:
            wave = instrument(sample_rate=sample_rate)
        else:
            wave = []
        slots.append(fit(wave, n))
    return sum(slots, [])

def render_timed_tracks(tracks, sample_rate=SR):
    waves = []
    for pattern, instrument, step_lengths in tracks:
        wave = render_timed_pattern(
            pattern, instrument, step_lengths, sample_rate=sample_rate
        )
        waves.append(wave)
    return mix_tracks(waves)

bpm = 90
s = round(60 / bpm / 4 * SR)
long = round(1.3 * s)
short = 2 * s - long
step_lengths = [long, short] * 8

tracks = [
    ("x......x..x.....", kick, step_lengths),
    ("....x.......x...", snare, step_lengths),
    ("xxxxxxxxxxxxxxxx", closed_hat, step_lengths),
]
phrase = render_timed_tracks(tracks)
play(phrase * 4)