Lesson 1.1Module 1: Music as a time series30 minBeginner

What is a time series? Your first song as data

Build a drum click in Python, turn it into a loudness curve, write a melody down as data and simulate a new single's streams, and see why the order of the numbers is the whole point.

Part of the free course Music as Data: Time Series with Python · taught by Terence D. Agbeyegbe and Tone Agbeyegbe

Music happens in time. Every beat, every note, every stream of a new single comes with a timestamp. In this first lesson you'll build a drum click in Python, look at it the way a computer does, and meet the idea that runs through this whole course: the time series.

What a time series is

A time series is a list of measurements recorded in time order. Each value comes with a time, and the order matters.

You already know plenty of them: a city's temperature every hour, a country's unemployment rate every month, a stock price every second. Music is full of them too:

  • The sound itself. A digital recording is a long list of numbers that measure air pressure. A CD stores 44,100 of them per second for each channel.
  • Loudness. How loud a track is, measured every few milliseconds, gives the curve you see in a waveform display.
  • The notes. A melody is a sequence of notes, each with a start time, a pitch and a length. That's what MIDI files store.
  • The business. A song's daily streams, its weekly chart position and its monthly royalty statements are all time series.

What makes time series special is that the order carries information. Shuffle a class's exam scores and the class average stays the same, and nothing is lost. Shuffle the numbers in a song and you're left with noise. We'll prove that at the end of the lesson.

Two kinds of music data

This course works with two families of music data, and it helps to separate them from the start.

  1. Signals are measured at a fixed rate, very fast: audio samples (thousands per second) and loudness or pitch curves (every few milliseconds). They're the raw material of audio software and of AI music models.
  2. Events and counts are slower: notes (which start whenever the music says so, not at fixed intervals), daily streams, weekly charts, monthly sales. They're the raw material of music analytics and the music business.

The same tools work on both. Trend, seasonality, smoothing and autocorrelation mean the same thing whether the series is a drum loop or a song's streaming numbers. That's why we'll keep switching between the two.

Setting up

You need Python 3 and three free libraries: numpy (fast arrays of numbers), pandas (tables and time series) and matplotlib (charts). Install them once, from a terminal:

Terminal
pip install numpy pandas matplotlib

Then start Python, or open a Jupyter notebook, and load them:

Python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Make a beat

Let's build four seconds of a click track at 120 beats per minute, the kind of metronome a drummer records to. We'll make it from scratch, so you can see that sound really is just numbers.

Python
sr = 22050        # sample rate: 22,050 measurements per second
bpm = 120         # tempo: 120 beats per minute
seconds = 4

t = np.arange(int(sr * seconds)) / sr     # the time of every sample, in seconds
audio = np.zeros_like(t)                  # start with silence

beat_len = 60 / bpm                       # 0.5 seconds between beats
for i, start in enumerate(np.arange(0, seconds, beat_len)):
    accent = i % 4 == 0                   # beat 1 of each bar of four
    pitch = 1500 if accent else 1000      # a higher, louder click on beat 1
    level = 1.0 if accent else 0.6
    n = int(0.05 * sr)                    # each click lasts 50 milliseconds
    k = int(start * sr)                   # the sample where this click starts
    tt = np.arange(n) / sr
    click = level * np.sin(2 * np.pi * pitch * tt) * np.exp(-tt * 80)
    audio[k:k + n] += click[: len(audio) - k]

print(len(audio), "samples")

That prints 88200 samples: 22,050 per second for 4 seconds. Each click is a short sine wave (a pure tone) that fades out quickly, which is roughly what a metronome's tick is. Now plot it:

Python
plt.figure(figsize=(10, 3))
plt.plot(t, audio, linewidth=0.5)
plt.xlabel("Time (seconds)")
plt.ylabel("Amplitude")
plt.title("A 120 BPM click track: 88,200 numbers in time order")
plt.show()
The click track as a waveform: eight spikes, half a second apart, with a taller spike at the start of each bar.
The click track as a waveform: eight spikes, half a second apart, with a taller spike at the start of each bar.

There are the eight beats, half a second apart, with the accented beat 1 of each bar standing taller. You can also save the numbers as a WAV file and listen to them:

Python
import wave

pcm = (audio / np.abs(audio).max() * 0.8 * 32767).astype(np.int16)   # scale to 16-bit integers, like a CD
with wave.open("click_120bpm.wav", "wb") as f:
    f.setnchannels(1)       # mono
    f.setsampwidth(2)       # 2 bytes = 16 bits per sample
    f.setframerate(sr)
    f.writeframes(pcm.tobytes())
Listen: the click track you just built.

Zoom in: the samples are the data

A waveform looks like a smooth line, but it's really separate points. Zoom in on the first five milliseconds:

Python
zoom = t < 0.005
plt.figure(figsize=(10, 3))
plt.plot(t[zoom] * 1000, audio[zoom], marker="o", markersize=3, linewidth=0.8)
plt.xlabel("Time (milliseconds)")
plt.ylabel("Amplitude")
plt.title("The first 5 milliseconds: every dot is one sample")
plt.show()
A close-up of the start of the first click: about 110 dots tracing a sine wave.
A close-up of the start of the first click: about 110 dots tracing a sine wave.

Each dot is one measurement, taken 1/22,050 of a second after the one before. This is a time series in its purest form: equally spaced values whose order is everything.

From samples to a loudness curve with pandas

88,200 numbers is a lot to look at, and individual samples swing between positive and negative, so they don't tell you directly how loud the sound is. A common fix is to measure loudness over short windows using the root mean square (RMS): square the samples, average them over the window, and take the square root.

This is where pandas comes in. Give the samples a time index, and pandas can regroup them by time for you:

Python
signal = pd.Series(audio, index=pd.to_timedelta(t, unit="s"))

loudness = (signal ** 2).resample("20ms").mean() ** 0.5    # RMS loudness every 20 ms
print(len(signal), "samples ->", len(loudness), "loudness values")

plt.figure(figsize=(10, 3))
plt.plot(loudness.index.total_seconds(), loudness.values)
plt.xlabel("Time (seconds)")
plt.ylabel("Loudness (RMS)")
plt.title("The same beat as a loudness curve, one value every 20 ms")
plt.show()
The loudness curve: eight sharp peaks every half-second, the first and fifth taller.
The loudness curve: eight sharp peaks every half-second, the first and fifth taller.

resample("20ms") groups the samples into 20-millisecond bins, just as you might group daily sales into weeks. We've gone from 88,200 values to 200, and the beat is easier to see than ever. The repeating pattern, a peak every 0.5 seconds, is what tempo-detection software looks for. In Module 6 you'll find the tempo automatically with autocorrelation, the same idea those tools use.

Notes are a time series too

Now write a melody down as data. Here are the first two lines of "Twinkle, Twinkle, Little Star" (a traditional tune, so free to use), with pitches as MIDI note numbers. In MIDI, 60 is middle C and each step up is one semitone.

Python
pitches = [60, 60, 67, 67, 69, 69, 67, 65, 65, 64, 64, 62, 62, 60]
beats   = [1,  1,  1,  1,  1,  1,  2,  1,  1,  1,  1,  1,  1,  2]    # how long each note lasts

notes = pd.DataFrame({"pitch": pitches, "beats": beats})
notes["duration_s"] = notes["beats"] * beat_len                      # at 120 BPM, 1 beat = 0.5 s
notes["onset_s"] = notes["duration_s"].cumsum() - notes["duration_s"]  # each note starts when the last one ends
names = {60: "C", 62: "D", 64: "E", 65: "F", 67: "G", 69: "A"}
notes["name"] = notes["pitch"].map(names)
print(notes.head(8))
Python
plt.figure(figsize=(10, 3))
plt.barh(notes["pitch"], notes["duration_s"], left=notes["onset_s"], height=0.8)
for _, n in notes.iterrows():
    plt.text(n["onset_s"] + 0.05, n["pitch"], n["name"], va="center", fontsize=8, color="white")
plt.xlabel("Time (seconds)")
plt.ylabel("MIDI pitch")
plt.title("Twinkle, Twinkle as data: a 'piano roll'")
plt.show()
A piano-roll chart: bars stepping up from C to A and back down to C, with longer bars at the end of each line.
A piano-roll chart: bars stepping up from C to A and back down to C, with longer bars at the end of each line.

This is the piano-roll view you'll recognise from any music software. Notice one difference from the click track: the notes are not equally spaced. Look at the gaps between start times:

Python
print(notes["onset_s"].diff().value_counts())

Twelve notes start 0.5 seconds after the one before, but the note after the long G in the middle starts 1.0 second later. Notes are events: they happen when the music says so. Later lessons show how to turn events like these into an evenly spaced series when a method needs one.

A new single's streams

Now the business side. Below is a simulated daily stream count for a new single released on a Friday. The numbers are made up so that you know exactly what's in them: a big launch that fades, a small lift every Friday and Saturday, and random noise. In Module 2 we'll use the same recipe to learn how to pull those parts back out of real data.

Python
rng = np.random.default_rng(42)                     # fixed seed, so you get the same numbers we did
days = pd.date_range("2026-01-02", periods=120, freq="D")    # Friday 2 January 2026

trend = 50_000 * np.exp(-np.arange(120) / 45) + 8_000        # launch spike, slow fade, steady floor
weekly = 1 + 0.12 * np.isin(days.day_of_week, [4, 5])           # +12% on Fridays and Saturdays
noise = rng.normal(1, 0.05, 120)                              # day-to-day randomness, about 5%

streams = pd.Series((trend * weekly * noise).round(), index=days, name="streams")
print(streams.head())

plt.figure(figsize=(10, 3.2))
plt.plot(streams, linewidth=1, label="Daily streams")
plt.plot(streams.resample("W").mean(), linewidth=2.5, label="Weekly average")
plt.ylabel("Streams per day")
plt.title("A simulated new single: trend, a weekly rhythm and noise")
plt.legend()
plt.show()
Simulated daily streams falling from about 65,000 to about 12,000 over four months, with a small zigzag each week, and a smooth weekly-average line.
Simulated daily streams falling from about 65,000 to about 12,000 over four months, with a small zigzag each week, and a smooth weekly-average line.

The daily line zigzags with the weekly rhythm. The weekly average smooths that away and shows the trend underneath. Trend, a repeating ("seasonal") pattern and noise are the three ingredients of most time series, in music or anywhere else, and Module 2 is all about them.

Why the order matters

Here's the proof promised at the start. Take the loudness curve and shuffle its 200 values into a random order:

Python
shuffled = pd.Series(rng.permutation(loudness.values), index=loudness.index)

print("mean:", round(loudness.mean(), 4), "vs", round(shuffled.mean(), 4))
print("std: ", round(loudness.std(), 4), "vs", round(shuffled.std(), 4))

fig, ax = plt.subplots(2, 1, figsize=(10, 4), sharex=True)
ax[0].plot(loudness.index.total_seconds(), loudness.values)
ax[0].set_title("In time order: a steady beat")
ax[1].plot(shuffled.index.total_seconds(), shuffled.values, color="C1")
ax[1].set_title("Same 200 values, shuffled: no beat")
ax[1].set_xlabel("Time (seconds)")
plt.tight_layout()
plt.show()
Two loudness curves: the top one with a regular beat, the bottom one with the same values scattered at random.
Two loudness curves: the top one with a regular beat, the bottom one with the same values scattered at random.

The mean and standard deviation are identical, because the shuffled series contains exactly the same numbers. To ordinary statistics the two are the same data. But one is a beat and the other is noise. Everything that made it music was in the order, and time-series analysis is the set of tools for studying that order.

Key ideas

  • A time series is a set of measurements in time order. The order carries information that ordinary statistics ignore.
  • Music gives us two kinds: signals (audio and loudness, measured at a fixed rate) and events and counts (notes, streams, charts).
  • In pandas, a time index lets you regroup data by time with resample(): samples into 20 ms loudness values, days into weeks.
  • Most series mix a trend, a repeating seasonal pattern and noise.

Try it yourself

  1. Change bpm to 90 and rebuild the click track. How far apart are the peaks in the loudness curve now?
  2. Change resample("20ms") to "100ms". What happens to the beat, and why?
  3. Add the next line of "Twinkle, Twinkle" (G G F F E E D, then G G F F E E D) to the melody. (MIDI: G = 67, F = 65, E = 64, D = 62.)
  4. In the streams simulation, change the weekly lift from 0.12 to 0.4. How does the daily line change? Does the weekly average change?

Next lesson: Sampling and aliasing: why a CD measures sound 44,100 times a second. What gets lost between the samples, and how a high note can come back as a low one.

The course

Music as Data: Time Series with Python

Course home
  1. 1Music as a time series

  2. 2Seeing patterns

  3. 3Decomposition and stationarity

  4. 4Testing a time series

  5. 5Missing values

    • 5.1Handling missing values in music data coming soon
  6. 6Autocorrelation and forecasting

    • 6.1Autocorrelation: finding the beat coming soon
    • 6.2Partial autocorrelation and lag plots coming soon
    • 6.3How forecastable is a hit? coming soon
  7. 7Smoothing and Granger causality

    • 7.1Smoothing: moving averages and loudness envelopes coming soon
    • 7.2Granger causality: does social-media buzz predict streams? coming soon
  8. 8From time series to AI music

    • 8.1From forecasting to generating: how AI music models predict what comes next coming soon