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.

Small instruments, connected

Lesson 03 · ACTAM 2026

Can we make a hi-hat, a kick and a snare from a few lists of numbers?

In lesson02 we gave sample recipes names and combined them into a melody. Now we will separate the sound source from the way it changes: noise or an oscillator supplies the signal; an envelope controls its amplitude or pitch.

We will start with a short noise burst. Each new instrument will give us a reason to build one more reusable tool.

How to use this notebook

Run the cells from top to bottom with Shift+Enter. Predict, listen and inspect a plot before changing the recipe. The “Your turn” prompts are short experiments; worked examples follow them.

This notebook is self-contained. We use the same IPython and Matplotlib environment as the earlier lessons, plus Python's standard-library random and math modules. Lists, comprehensions, functions and loops are our main building blocks.

play is a small convenience for rendering samples. Its implementation can later use sounddevice; our synthesis functions return ordinary sample lists. Click each player to listen and begin at low volume. Automatic normalisation is disabled so comparisons preserve the chosen amplitudes.

from IPython.display import Audio, display
from matplotlib import pyplot as plt
from random import random
from math import exp

SR = 48_000

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

def silence(duration=0.5, sample_rate=SR):
    return [0.0] * round(duration * sample_rate)

1. A hi-hat begins with noise

Lesson02 used a toy pseudorandom generator to explore state and loops. Today we use random(): each call returns a new pseudorandom value in the interval from 0 up to, but not including, 1.

For audio, we shift and scale that range around zero. 2 * random() - 1 lies between −1 and +1; multiplying by 0.15 sets the amplitude.

What happens if this sound lasts a whole second?

long_noise = [0.15 * (2 * random() - 1) for _ in range(SR)]
play(long_noise)

A second is long for a closed hi-hat. Let's try 50 milliseconds.

We will reuse the beginning of the same noise recording, so the first comparison changes only duration.

duration = 0.05
n = round(duration * SR)
burst = long_noise[:n]
play(burst)

Your turn · Listen to the ending

Does the burst suggest a percussion sound? What happens at the end?

Describe the difference between a sound that stops abruptly and one whose vibrations die away. How could we express that difference using multiplication?

2. Let the amplitude fall

Multiply the samples by a factor that starts at 1 and decreases to 0. This sequence of gains is an amplitude envelope.

For this multi-sample burst, i / (n - 1) goes from exactly 0 to exactly 1. The signal and the envelope have the same length.

linear = [1 - i / (n - 1) for i in range(n)]
hat_linear = [burst[i] * linear[i] for i in range(n)]
play(hat_linear)
time = [i / SR for i in range(n)]
fig, axes = plt.subplots(3, 1, figsize=(9, 6), sharex=True)
axes[0].plot(time, burst, linewidth=0.6)
axes[0].set_ylabel("Noise")
axes[1].plot(time, linear)
axes[1].set_ylabel("Gain")
axes[2].plot(time, hat_linear, linewidth=0.6)
axes[2].set_ylabel("Result")
axes[2].set_xlabel("Time (seconds)")
fig.suptitle("The sound source multiplied by its envelope")
fig.tight_layout()
plt.show()

The middle plot is a control signal. Its values tell us how much of the noise to keep at each instant.

A gain of 1 leaves a sample unchanged, 0.5 halves it, and 0 makes it silent. We usually inspect this envelope as a plot; listening to the slowly changing gain itself would not demonstrate the percussion sound we are shaping.

Another shape: exponential decay

A linear envelope loses the same amount of gain in each equal time interval. An exponential envelope loses the same fraction of its current gain.

We describe its speed with a time constant, tau, measured in seconds:

At , the gain is , about 0.368. A larger tau gives a slower decay.

tau = 0.012
exponential = [exp(-(i / SR) / tau) for i in range(n)]
hat_exponential = [burst[i] * exponential[i] for i in range(n)]

plt.figure(figsize=(9, 3))
plt.plot(time, linear, label="Linear")
plt.plot(time, exponential, label="Exponential: tau = 0.012 s")
plt.xlabel("Time (seconds)")
plt.ylabel("Gain")
plt.legend()
plt.tight_layout()
plt.show()
# The same source noise, first with a linear decay, then an exponential decay.
play(hat_linear + silence(0.25) + hat_exponential)

Why an exponential?

A simple model says: the larger the current amplitude, the faster it decreases.

The solution is . Over a small time interval , we can read the model as

Some idealised damped oscillators have an exponentially decaying amplitude. This makes the envelope a useful starting point for percussion. Real cymbals and membranes have many vibration modes and more complicated decays; this is a sound-design model, not a complete physical simulation.

Which envelope do you prefer for this sound?

Connecting this to a decay rate per sample

A recipe such as exp(-i * decaying_rate) measures decay against the sample index. Since time is i / sample_rate, the two descriptions match when

decaying_rate = 1 / (sample_rate * tau).

At 48,000 samples per second, a rate of 0.001 per sample corresponds to tau = 1 / (48_000 * 0.001), about 0.0208 seconds.

Expressing tau in seconds makes its meaning stay the same when we change the sample rate.

Your turn · Length and decay are different choices

Keep the same source noise and compare tau = 0.005, 0.012 and 0.04 seconds.

  1. Which sound loses amplitude most quickly?
  2. Does an exponential envelope reach exactly zero at the end of our buffer?
  3. Would making the buffer longer necessarily make the sound noticeably longer?

Try before reading the answer.

Discussion

The smallest tau gives the quickest decay. An exponential remains positive at every finite time; cutting the buffer ends it at a nonzero value. Extending a buffer far beyond several time constants mainly adds samples with very small amplitudes. Duration and decay speed are separate controls.

3. A source and an envelope we can reuse

We could write a new comprehension for every combination. Instead, let the source and envelope be separate lists.

A VCA is a voltage-controlled amplifier. In our digital model, a list of gain values controls the amplitude of another list, sample by sample. There is no physical control voltage in this notebook, but the signal relationship is the same.

Before writing the VCA, we need a way to pair corresponding values.

samples = [0.2, -0.4, 0.6]
gains = [1.0, 0.5, 0.0]
list(zip(samples, gains))

zip pairs values by position: first with first, second with second, and so on. Each pair is a tuple, as in our pitch/duration pairs from lesson02.

In for x, gain in zip(samples, gains), the two names receive the two values of each pair. This is called unpacking.

[x * gain for x, gain in zip(samples, gains)]

What if the lists have different lengths?

By default, zip stops when the shorter input runs out. That could silently shorten a sound.

Try the tiny example below. Our VCA will require equal lengths and report a mismatch explicitly.

list(zip([1, 2, 3], [10, 20]))
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)]

if runs its indented block only when the condition is true. != means “not equal”. raise ValueError(...) stops the call with a message explaining the problem.

This small check makes an important assumption visible: our two lists describe the same instants at the same sample rate.

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 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)]

max(1, n - 1) keeps the linear envelope's denominator nonzero for very short buffers. For two or more samples, its endpoints are exactly 1 and 0; a single-sample envelope contains only the starting gain.

For all our recipes, use nonnegative durations, positive sample rates and amplitudes between 0 and 1. These are the intended input limits; the functions check only the specific mistakes we discuss in class.

source = noise(0.08)
linear_hat = vca(source, envelope_lin(0.08))
exponential_hat = vca(source, envelope_exp(0.08, tau=0.015))
play(linear_hat + silence(0.25) + exponential_hat)

Your turn · Connect the tools

Make one source noise buffer of 0.2 seconds. Shape that same buffer with two different envelopes and compare them.

Then, in a separate scratch cell, pass an envelope of the wrong duration to vca. Read the error and correct the duration.

Which information does a plain list not carry? It does not record its sample rate. Matching lengths is necessary, but we must also use the same time scale.

4. Closed and open hats

Try a short, fast decay and a longer, slower decay. We are changing both the available duration and the envelope's time constant.

These are simple noise-based approximations. A real hi-hat also has a complex spectrum and interactions between its cymbals.

closed_candidate = vca(
    noise(0.06),
    envelope_exp(0.06, tau=0.010),
)
open_candidate = vca(
    noise(0.30),
    envelope_exp(0.30, tau=0.070),
)
play(closed_candidate + silence(0.25) + open_candidate)

What happens if you extend the closed candidate to 0.30 seconds but keep its time constant at 0.010? Predict before trying.

Most of its audible energy would still be concentrated near the start. The slower decay is an important part of the open-hat impression.

5. A kick needs a pitch that moves

For a first electronic kick, we can use a low oscillator whose frequency falls quickly, together with an amplitude envelope.

The square-wave recipe from lesson02 repeated a fixed, rounded period. We now want to take frequency values from another list.

One approach is to read a frequency, append a negative and positive half-period, then advance the index by the block length. But that updates pitch only at block boundaries, rounds each period and may overshoot the requested duration.

Let's instead keep track of where we are in the cycle. This will let us produce one sample for every frequency value.

Step 1 · Keep a clock inside the oscillator

Call the position within a cycle phase, measured from 0 up to 1:

  • phases below 0.5 give the negative half of our square wave;
  • phases from 0.5 up to 1 give the positive half;
  • after one cycle, we wrap back to the start.

At frequency and sample rate , one sample advances phase by cycles. At 4 Hz and 16 samples per second, that is a quarter-cycle per sample.

phase = 0.0
phases = []
toy_wave = []
for _ in range(12):
    phases.append(phase)
    toy_wave.append(-1 if phase < 0.5 else 1)
    phase = (phase + 4 / 16) % 1

print("Phases:", phases)
print("Samples:", toy_wave)

a if condition else b is an expression: choose a when the condition is true and b otherwise.

We generate the current sample, then advance phase. The remainder operation % 1 keeps phase in the interval from 0 up to 1.

Now apply the same recipe to an audible fixed frequency.

f = 120
duration = 0.2
phase = 0.0
fixed_tone = []
for _ in range(round(duration * SR)):
    fixed_tone.append(-0.15 if phase < 0.5 else 0.15)
    phase = (phase + f / SR) % 1

play(fixed_tone)

Step 2 · Let a list control the frequency

Replace the fixed f in the phase update with the next value from a frequency list. Keep the current phase between iterations.

The length of that list determines the output duration. We no longer pass a separate duration that could disagree with it.

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
steady_pitch = [120 for _ in range(round(0.2 * SR))]
play(square_wave_f(steady_pitch))

We have built a frequency-controlled oscillator: the digital analogue of a VCO, a voltage-controlled oscillator. A VCF is a voltage-controlled filter, which is a different tool.

The phase recipe removes the fixed integer-period restriction from lesson02. It still produces a naive square wave with strong high harmonics, which can alias. It is useful for hearing the control relationship; it is not a band-limited synthesizer or an acoustic drum model.

Your turn · Follow the oscillator

  1. In the toy example, change 4 Hz to 2 Hz. Predict the phase increment and the new samples.
  2. Use a constant frequency list at 240 Hz and compare it with 120 Hz.
  3. Why must phase = 0.0 be outside the loop?
Discussion

At 2 Hz and 16 samples per second, phase advances by 1/8 of a cycle per sample. Doubling frequency doubles the phase increment. Resetting phase inside each iteration would discard the oscillator's progress and keep producing the same starting value.

6. Use an envelope for pitch

An envelope is just a list of numbers. We can turn its values into frequencies:

When , frequency is . As the envelope tends towards zero, frequency approaches .

A positive final frequency avoids letting the kick's pitch fall all the way to zero.

duration = 0.25
pitch_shape = envelope_exp(duration, tau=0.025)
pitch = [45 + (180 - 45) * value for value in pitch_shape]
body = square_wave_f(pitch)

plt.figure(figsize=(9, 3))
plt.plot([i / SR for i in range(len(pitch))], pitch)
plt.xlabel("Time (seconds)")
plt.ylabel("Frequency (Hz)")
plt.title("An envelope mapped from gain values to a pitch trajectory")
plt.tight_layout()
plt.show()

play(body)

Now give the sound a separate amplitude decay. The pitch envelope and amplitude envelope need not move at the same speed.

amplitude_shape = envelope_exp(duration, tau=0.060)
kick_candidate = vca(body, amplitude_shape)
play(kick_candidate)

Your turn · Two envelopes, two jobs

  1. Keep the pitch trajectory and make the amplitude decay faster.
  2. Keep the amplitude envelope and make the pitch fall more slowly.
  3. Compare the result with a fixed low frequency and the same amplitude envelope.

Which change makes a longer tail? Which makes the downward pitch movement more noticeable? Use the same duration in each comparison.

A first kick function

Wrap the connections we have just made. Every internal generator receives the same 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)

play(kick_raw())

7. A snare has two components

For a simple electronic snare, combine a short pitched body with a noisy component suggesting the snare wires.

This time pitch falls from about 300 Hz towards 180 Hz. The noise will lose amplitude more slowly than the body.

Let's construct the components separately, then listen to each one.

duration = 0.20
pitch = [
    180 + 120 * value
    for value in envelope_exp(duration, tau=0.010)
]
snare_body = vca(
    square_wave_f(pitch, amplitude=0.15),
    envelope_exp(duration, tau=0.025),
)
snare_noise = vca(
    noise(duration, amplitude=0.15),
    envelope_exp(duration, tau=0.055),
)
display(play(snare_body))
display(play(snare_noise))

How do we put the two sounds on top of one another?

For lists, + concatenates. We need addition of corresponding samples instead.

a = [0.1, 0.2, -0.1]
b = [0.3, -0.1, 0.0]
print("One after another:", a + b)
print("At the same time:", [x + y for x, y in zip(a, b)])

8. A mixer, with two gain controls

Like the VCA, our mixer will work on equal-length buffers at the same sample rate. It scales each input, then adds corresponding samples.

If one sound is shorter, explicitly pad it with silence before mixing. This version reports unequal lengths instead of silently truncating the longer input.

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)]

snare_candidate = mix(snare_body, snare_noise, ga=1.0, gb=0.5)
play(snare_candidate)

Leave room for the sum

Mixing can make peaks larger than either input alone. If both component signals stay within ±0.15, gains of 1 and 0.5 keep their sum within ±0.225.

Our playback examples expect samples within −1 to +1. Use moderate source amplitudes and mixer gains; avoid normalising each comparison, which would conceal gain changes.

The gains set the balance between the body and the noisy wires. They are musical controls.

print("Snare peak:", max(abs(value) for value in snare_candidate))

Your turn · Change the snare

Reuse the stored snare_body and snare_noise so repeated calls to the random generator do not change the comparison.

  1. Try noise gains of 0, 0.5 and 1.
  2. Make the noise decay more slowly while leaving the pitched body unchanged.
  3. Listen to concatenation and mixing of the same two components. Compare their lengths.
Discussion

A zero noise gain leaves only the pitched body. More noise gain emphasises the noisy component. Concatenating two 0.2-second buffers lasts 0.4 seconds; mixing them lasts 0.2 seconds. A longer decay time keeps more noise near the end, but the buffer still ends after 0.2 seconds.

9. Finish the edges, then package the instruments

An exponential tail does not reach zero exactly, and our noise and square waves can start at nonzero amplitudes. Very abrupt buffer boundaries can click.

Before packaging the kit, we can multiply by one more gain shape: a brief fade at the start and the end. This rounds the edges of the buffer; it does not replace the main envelope.

The helper below is a finishing tool. Read it after you understand the instrument connections, or keep it as a provided utility on the first pass.

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)

For each sample, min chooses the smallest of full gain, the rising attack ramp and the falling release ramp. The first and last samples become zero.

Very short buffers may never reach full gain; a one-sample buffer becomes silence. Use nonnegative fade durations. Even with zero requested fade time, this helper reserves at least one sample at each edge.

Now define four instruments using the same tools. Their amplitude parameter is a common scale control, not a promise of equal perceived loudness.

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(
    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 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,
    )

Listen to the kit

Each call makes a list of samples. The hats and snare contain newly generated noise; calling them again gives another realisation.

Try one instrument at a time, then listen to all four in sequence.

closed = closed_hat()
opened = open_hat()
bass = kick()
snare_hit = snare()

demo = (
    closed + silence(0.25)
    + opened + silence(0.25)
    + bass + silence(0.25)
    + snare_hit
)
play(demo)

10. Your turn · A musical conversation

Make a short call and response with your kit.

  1. Use concatenation and silence to place hits one after another.
  2. Try a kick and a closed hat starting together. Pad the shorter list to the longer list's length, then mix them.
  3. Change one instrument's envelope to give the answer a different character.
  4. Save the version you prefer and name the control you changed.

Keep each rhythmic slot the same total length. We will leave a general pattern notation and sequencer for a later step.

A worked starting point

A half-second slot is long enough for our default hits. The first slot contains a kick and closed hat at the same time. The second contains a snare.

hat_layer = closed + [0.0] * (len(bass) - len(closed))
combined_hit = mix(bass, hat_layer)

slot_samples = round(0.5 * SR)
first_slot = combined_hit + [0.0] * (slot_samples - len(combined_hit))
second_slot = snare_hit + [0.0] * (slot_samples - len(snare_hit))

rhythm = (first_slot + second_slot) * 2
print("Rhythm duration:", len(rhythm) / SR, "seconds")
play(rhythm)

This example assumes each hit fits inside its slot and that the kick is at least as long as the hat. Revisit those assumptions if you change the durations: multiplying a list by a negative number returns an empty list; it does not trim a long sound.

Repeating the stored slots repeats exactly the same samples, including the noise. Generating fresh hits would create small differences on each repetition.

What have we built?

A source, an amplitude envelope, a frequency trajectory and a mixer all use the same representation: lists of numbers with a shared time scale.

Their meaning depends on the connection. An envelope can control gain, or we can map it to frequency. Multiplication shapes a signal; sample-by-sample addition combines simultaneous sounds; concatenation places them in time.

We now have four small instruments assembled from reusable computations. Keep one sound, one rhythm and a sketch of the connections that produced them.