Lesson 1.3Module 1: Music as a time series35 minBeginner

Loading music data into pandas: audio, MIDI and streaming numbers

Open three real file types, a stereo WAV, a MIDI file and a CSV of streaming numbers, and turn each into a pandas time series you can plot, check and resample.

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

So far we've made our own data. Real work starts with files: a recording from a session, a MIDI file from your music software, a spreadsheet of streams exported from a dashboard. This lesson opens one of each and turns it into a pandas time series. Each format stores time differently, and the hardest part of loading music data is getting the time right.

The files

Download the three practice files and put them in the folder you run Python from:

  • chords_stereo.wav: six seconds of audio, CD quality, in stereo. Four chords (C, G, A minor, F) on the left channel, and a bass line on the right.
  • twinkle.mid: the first two lines of "Twinkle, Twinkle, Little Star" (a traditional tune), with a melody and a bass part.
  • streams.csv: simulated daily streams for two made-up tracks over 90 days. A few days are missing on purpose, as they often are in real exports.
Listen: chords_stereo.wav. With headphones, the chords are in your left ear and the bass in your right.

You'll need one more library for MIDI files, mido:

Terminal
pip install mido
Python
import wave

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

Audio: reading a WAV file

A WAV file has a short header describing the audio, followed by the samples. Python's built-in wave module reads both:

Python
with wave.open("chords_stereo.wav", "rb") as f:
    sr = f.getframerate()          # samples per second, per channel
    channels = f.getnchannels()    # 1 = mono, 2 = stereo
    width = f.getsampwidth()       # bytes per sample: 2 = 16-bit
    n = f.getnframes()             # number of samples per channel
    raw = f.readframes(n)          # the samples themselves, as raw bytes

print(f"{sr:,} Hz, {channels} channels, {8 * width}-bit, {n:,} frames = {n / sr:.1f} seconds")

Always read the header before the samples. It tells you the three things you need to turn bytes into a time series: how many channels, how many bytes per sample, and the sample rate, which is what converts sample numbers into seconds.

In a stereo file the samples are interleaved: left, right, left, right. numpy can read the bytes as 16-bit integers and fold them into two columns:

Python
samples = np.frombuffer(raw, dtype=np.int16).reshape(-1, channels) / 32768   # scale to -1 … +1

audio = pd.DataFrame(samples, columns=["left", "right"],
                     index=pd.to_timedelta(np.arange(n) / sr, unit="s"))
audio.index.name = "time"
print(audio.head())
print(audio.abs().max())

Dividing by 32,768 rescales the 16-bit integers (which run from −32,768 to 32,767) to the range −1 to +1, the usual convention for audio. The index turns each row number into a time, just as in lesson 1.1. Now the file is a two-column time series:

Python
loud = (audio ** 2).resample("50ms").mean() ** 0.5          # RMS loudness of each channel, every 50 ms

fig, ax = plt.subplots(2, 1, figsize=(10, 4.4), sharex=True)
step = 20                                                   # plot every 20th sample: plenty for the eye
secs = audio.index.total_seconds()
ax[0].plot(secs[::step], audio["left"].values[::step], linewidth=0.4, label="Left: chords")
ax[0].plot(secs[::step], audio["right"].values[::step], linewidth=0.4, alpha=0.8, label="Right: bass")
ax[0].set_title("chords_stereo.wav: both channels")
ax[0].legend(loc="upper right", fontsize=8)
ax[1].plot(loud.index.total_seconds(), loud["left"], label="Left")
ax[1].plot(loud.index.total_seconds(), loud["right"], label="Right")
ax[1].set_title("Loudness every 50 ms: four chords, each struck and fading")
ax[1].legend(loc="upper right", fontsize=8)
ax[1].set_xlabel("Time (seconds)")
plt.tight_layout()
plt.show()
Two charts: the stereo waveform, with four blocks of sound, and the loudness of each channel jumping up every 1.5 seconds and then fading.
Two charts: the stereo waveform, with four blocks of sound, and the loudness of each channel jumping up every 1.5 seconds and then fading.

Four chords, one every 1.5 seconds, each struck and then fading. The resample step is the same one you used in lesson 1.1. Once audio is in a time-indexed DataFrame, everything pandas can do with time works on it.

Other audio formats. The wave module reads uncompressed WAV files only. For MP3, FLAC or OGG, install soundfile or librosa (for example librosa.load("song.mp3", sr=None)). They hand you the same thing: a numpy array of samples and a sample rate, and from there everything in this lesson applies.

MIDI: from messages to a table of notes

A MIDI file doesn't contain sound. It contains instructions: "start playing middle C now, this hard", then "stop playing middle C". Let's look inside:

Python
mid = mido.MidiFile("twinkle.mid")
print("Tracks:", [t.name for t in mid.tracks])
print("Ticks per beat:", mid.ticks_per_beat)
print("Length:", round(mid.length, 2), "seconds")
for msg in mid.tracks[1][:6]:
    print(msg)

The first messages of the melody track look like note_on channel=0 note=60 velocity=90 time=0 followed by note_off channel=0 note=60 velocity=0 time=432. Three things to know:

  • note is the pitch, as a MIDI number (60 = middle C).
  • velocity is how hard the note was played, from 1 to 127.
  • time is not a clock time. It's the gap since the previous message, counted in ticks, and the file says how many ticks make a beat (here 480). The tempo, also stored in the file, converts beats to seconds.

That's a lot of conversion to do by hand. Fortunately, looping over the whole MidiFile gives you every message from every track in order, with time already converted to seconds since the previous message. To get a table of notes, keep a running clock, remember when each note started, and write a row when it stops:

Python
rows, now, started = [], 0.0, {}
for msg in mid:                                    # all tracks, in time order; msg.time is in seconds
    now += msg.time
    if msg.type == "note_on" and msg.velocity > 0:
        started[(msg.channel, msg.note)] = (now, msg.velocity)
    elif msg.type in ("note_off", "note_on"):      # note_off, or note_on with velocity 0 (also means "stop")
        start, velocity = started.pop((msg.channel, msg.note))
        rows.append({"onset_s": round(start, 3), "duration_s": round(now - start, 3),
                     "pitch": msg.note, "velocity": velocity,
                     "part": "melody" if msg.channel == 0 else "bass"})

notes = pd.DataFrame(rows).sort_values(["onset_s", "pitch"]).reset_index(drop=True)
print(notes.head(8))
print(len(notes), "notes")

Notice the second branch. Many MIDI files never send note_off. They send note_on with velocity 0, which means the same thing, so robust code has to accept both.

Python
plt.figure(figsize=(10, 3.4))
for part, color in [("melody", "C0"), ("bass", "C1")]:
    p = notes[notes["part"] == part]
    plt.barh(p["pitch"], p["duration_s"], left=p["onset_s"], height=1.6, color=color, label=part)
plt.xlabel("Time (seconds)")
plt.ylabel("MIDI pitch")
plt.title("twinkle.mid as a table of notes, drawn as a piano roll")
plt.legend(loc="upper right", fontsize=8)
plt.show()
A piano roll with the melody's short bars in the upper half and the bass's longer bars in the lower half.
A piano roll with the melody's short bars in the upper half and the bass's longer bars in the lower half.

Events into a regular series

The notes are events, as in lesson 1.1. Many time-series methods want evenly spaced values instead, so here's how to convert one to the other: count how many notes start in each half-second (one beat at 120 BPM).

Python
onsets = pd.Series(1, index=pd.to_timedelta(notes["onset_s"], unit="s"))
per_beat = onsets.resample("500ms").sum()
print(per_beat.values)

Now each beat has a number: 2 where a melody note and a bass note start together, 1 where only the melody moves, and 0 where nothing new begins. Choosing what to count (note starts, average pitch, total velocity) is a modelling decision, and it decides what your analysis can see.

A CSV of streams

Last, the business data. CSV files are the most common way to get numbers out of a dashboard, and pandas reads them with one line. The parse_dates option tells it that the date column holds dates, not text:

Python
streams = pd.read_csv("streams.csv", parse_dates=["date"])
print(streams.head())
print(streams.dtypes)
print(streams["track"].value_counts())

The file is in long format: one row per track per day, as most exports are. For time-series work you usually want wide format: one column per track, one row per date. pivot does it:

Python
wide = streams.pivot(index="date", columns="track", values="streams")
print(wide.shape)

Two tracks for 90 days should mean 90 rows, but there are only 89. A whole day is missing from the file, and pandas has no way of knowing. asfreq("D") tells it the data should be daily, which brings the missing days back as gaps (NaN, "not a number"):

Python
wide = wide.asfreq("D")
print(wide.shape)
print(wide.isna().sum())
print(wide[wide.isna().any(axis=1)])

Now you can see the full picture: one day missing for both tracks, and two more missing for "Slow Burn" only. Always check for gaps when you load a time series. Many methods quietly assume the rows are evenly spaced, and a missing day would shift everything after it. Module 5 covers what to do about gaps; for now, just find them.

Python
ax = wide.plot(figsize=(10, 3.4), linewidth=1.2, marker=".", markersize=3)
ax.set_ylabel("Streams per day")
ax.set_xlabel("")
ax.set_title("streams.csv (simulated): a fading launch and a slow climber, with gaps")
plt.show()
Two lines over three months: Night Drive starting high and fading, Slow Burn starting low and rising, with small breaks where days are missing.
Two lines over three months: Night Drive starting high and fading, Slow Burn starting low and rising, with small breaks where days are missing.

The gaps show as breaks in the lines. The two tracks also tell different stories: a launch that fades, and a song that grows by word of mouth. In lesson 1.4 we'll look at data like this across many tracks at once, which economists call panel data.

Key ideas

  • Audio files store samples plus a header. Read the header first: the channel count, the sample width and the sample rate are what turn bytes into a time series.
  • Stereo samples are interleaved: reshape them into one column per channel.
  • MIDI files store instructions, not sound. Times are gaps between messages, in ticks; mido converts them to seconds. A table of notes needs note starts matched with note stops, and a note_on with velocity 0 counts as a stop.
  • Converting events to a regular series (counting notes per beat, for example) is a modelling choice.
  • CSVs: use parse_dates, pivot long data to wide, then asfreq to reveal missing dates. Always check for gaps.

Try it yourself

  1. Resample the WAV's loudness every 1.5 seconds ("1500ms") instead of every 50 ms. How many values do you get, and why does each one line up with a chord?
  2. Change the note count to resample("250ms"). What do the zeros now tell you about the rhythm?
  3. Load a MIDI file of your own (any song exported from your music software) and draw its piano roll. Which instruments use which channels?
  4. Find the date of the highest-streaming day for each track with wide.idxmax(). Then compare each track's weekly average in its first and last full week, using wide.resample("W").mean().

Next lesson: Panel data: many songs, measured over time. Follow twelve songs at once, line them up by release day, and measure how fast each one fades.

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