Machine listening is how a computer turns audio into information, and it includes many of the other things we have talked about in this book: what does a machine need from acoustics, from psychoacoustics, from music theory, before it can say anything about a recording? This includes overviews of signal processing and machine learning but we will also briefly look at how the chain can be reversed to generate music. What is important to remember is that, unlike humans, a machine works entirely on numbers.
What machine listening is¶
Machine listening, also called computer audition, turns sound, whether music, speech or a soundscape, into structured information. The steps are the same for each: capture the audio, extract features that reflect how we hear, find events and boundaries, attach labels, and present the result.
Machine listening is the foundation of music information retrieval (MIR), a field focused on asking musical questions of recordings, and of today’s musical AI Müller, 2021.
As in the rest of the book, the examples below are generated with Python code, and many use the librosa audio processing library. These are standard tools in the MIR community. You are not expected to learn them in this course, but it is good to know the names.
Dig deeper: Python, Jupyter, and librosa
Python. Python is a programming language widely used for scientific computing, data analysis, and machine learning. Most of its power comes from libraries: general scientific ones (NumPy, SciPy, pandas), audio ones (librosa, Essentia, madmom), and machine learning ones (PyTorch, TensorFlow). Its clean syntax makes it quick to learn, and it runs almost anywhere.
Jupyter Notebooks. A Jupyter Notebook is a web-based document that mixes live code, text, figures, and results. Code sits in cells that run one at a time, with the output shown under each, which suits exploring data step by step and sharing the result. Notebooks support several languages (Python, R, Julia) and export to HTML and PDF. This book is written as Jupyter Notebooks.
librosa. The examples use librosa McFee et al., 2015, a general-purpose Python library for audio and music analysis.
The analysis pipeline¶
In the following, we will assume that we already have an audio recording in place. From that, we will look at a pipeline in four stages: cleaning the audio, extracting features, separating sources, and finding events and sections.
Audio input and preprocessing¶
Audio reaches the machine the way electroacoustics described it: through a signal from a microphone to one or more converters to be stored as a file of numbers. Before moving on to analysis, the file is usually resampled to a common sampling rate, normalised in level, and cleaned of hum and clicks, so that recordings become comparable and the later stages behave the same on each.
A system meant to listen the way people do has to model hearing as well as the signal. The ear analyses frequency in critical bands that widen towards the treble, hears loudness rather than level, and lets loud sounds mask quieter ones nearby; perceptual scales such as the mel scale and loudness models build some of this into the features. What such models leave out matters as much: a listener hears sources, intentions, meanings and emotions shaped by context, attention, memory and the body, while the system measures only the signal it is given.
The analysis starts where acoustics started: with a waveform, and with the Fourier transform that turns it into a spectrogram. The running example is an excerpt of John Coltrane’s My Favorite Things, whose onsets, beats and swing can be described with the vocabulary of time and rhythm.
Source
import librosa
from IPython.display import Audio, display
import librosa.display
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({
"font.size": 10,
"axes.titlesize": 11,
"axes.labelsize": 10,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"legend.fontsize": 9,
"figure.figsize": (10, 4),
"figure.dpi": 100,
"savefig.dpi": 150,
"axes.spines.top": False,
"axes.spines.right": False,
})
audio_path = "audio/week6_audio_ex_2_coltrane_myfavthings.mp3"
y, sr = librosa.load(audio_path, sr=22050, mono=True)
hop_length = 512
# Waveform (separate figure)
plt.figure(figsize=(10, 3.3))
try:
librosa.display.waveshow(y, sr=sr)
except AttributeError:
librosa.display.waveplot(y, sr=sr)
plt.title('Waveform')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.tight_layout()
plt.show()
# show a playbar for the loaded audio below the spectrogram
display(Audio(audio_path))
# Spectrogram (STFT -> dB) (separate figure)
plt.figure(figsize=(10, 3.3))
S = np.abs(librosa.stft(y, n_fft=2048, hop_length=hop_length))
S_db = librosa.amplitude_to_db(S, ref=np.max)
librosa.display.specshow(S_db, sr=sr, hop_length=hop_length, x_axis='time', y_axis='log', cmap='magma')
plt.title('Spectrogram (STFT, log-frequency)')
plt.ylabel('Frequency (Hz)')
plt.xlabel('Time (s)')
plt.colorbar(label='dB')
plt.tight_layout()
plt.show()


Figure: The running example, an excerpt of John Coltrane’s My Favorite Things: the waveform (top) and its log-frequency spectrogram (bottom), with the audio between them.
Different levels of features¶
Feature extraction turns a waveform or a spectrogram into numbers that say something about the sound. The features come in three levels, and each level draws on what we have discussed in earlier chapters:
Low-level features describe timbre and energy from moment to moment: the spectral centroid (the centre of gravity of the spectrum, heard as brightness), spectral flatness (noise against tone), bandwidth, and RMS level. These are the quantities of acoustics and psychoacoustics.
Mid-level features describe pitch and harmony: the chromagram, the constant-Q transform, and pitch contours. These are the tools of harmony and melody.
High-level features describe time: onset strength, the tempogram, beat tracking, and section boundaries. These belong to time and rhythm.
Let us now consider how we can extract some features from the example above.
Tempo¶
Estimating the tempo of a song is not straightforward, and can be challenging also for humans if there are many tempo changes and ambiguous metres. We start by creating a tempogram, which shows which tempi are prominent at each moment:
Source
import matplotlib.pyplot as plt
plt.rcParams.update({
"font.size": 10,
"axes.titlesize": 11,
"axes.labelsize": 10,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"legend.fontsize": 9,
"figure.figsize": (10, 4),
"figure.dpi": 100,
"savefig.dpi": 150,
"axes.spines.top": False,
"axes.spines.right": False,
})
# Tempogram (rhythmic autocorrelation)
onset_env = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop_length)
tempogram = librosa.feature.tempogram(onset_envelope=onset_env, sr=sr, hop_length=hop_length)
plt.figure(figsize=(10, 3.3))
librosa.display.specshow(tempogram, sr=sr, hop_length=hop_length, x_axis='time', y_axis='tempo', cmap='magma')
plt.colorbar(label='Autocorrelation')
plt.title('Tempogram (local tempo over time)')
plt.tight_layout()
plt.show()
Figure: Tempogram of the excerpt: the strength of each tempo (vertical axis, in BPM) at each moment, computed by autocorrelation of the onset curve.
The tempogram is hard to read directly, and also reflects the complexity of the music in question. To try to estimate the perceived tempo, we can smooth the tempogram and average across the bands to get a single running tempo estimate:
Source
from librosa.feature import rhythm
import matplotlib.pyplot as plt
plt.rcParams.update({
"font.size": 10,
"axes.titlesize": 11,
"axes.labelsize": 10,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"legend.fontsize": 9,
"figure.figsize": (10, 4),
"figure.dpi": 100,
"savefig.dpi": 150,
"axes.spines.top": False,
"axes.spines.right": False,
})
times = librosa.frames_to_time(np.arange(len(onset_env)), sr=sr, hop_length=hop_length)
tempo_est = librosa.feature.tempo(onset_envelope=onset_env, sr=sr, hop_length=hop_length)
# Instantaneous tempo: the strongest tempo in a short (2 s) autocorrelation window around each frame.
# The default window is 8 s, which already averages so much that smoothing it again changes nothing.
tempo_running = rhythm.tempo(onset_envelope=onset_env, sr=sr, hop_length=hop_length, aggregate=None, ac_size=2.0)
# Smooth the running estimate with a moving average of about 2 s
win = int(round(2.0 * sr / hop_length)) | 1
kernel = np.ones(win) / win
tempo_smooth = np.convolve(tempo_running, kernel, mode='same')
plt.figure(figsize=(10, 3.3))
plt.plot(times, tempo_running, color='gray', alpha=0.5, linewidth=0.8, label='Instantaneous tempo (2 s window)')
plt.plot(times, tempo_smooth, color='C1', linewidth=2, label='Smoothed running tempo (2 s moving average)')
plt.axhline(float(tempo_est[0]), color='k', linestyle='--', linewidth=1.5, label=f'Global tempo: {tempo_est[0]:.2f} BPM')
# Optionally mark beat times
if 'beat_times' in globals():
for bt in beat_times:
plt.axvline(bt, color='r', linestyle=':', alpha=0.25, linewidth=0.8)
plt.xlabel('Time (s)')
plt.ylabel('Tempo (BPM)')
plt.title('Running estimated tempo (per-frame) with smoothed curve')
plt.legend(loc='upper right')
plt.xlim(times[0], times[-1])
plt.tight_layout()
plt.show()

Figure: The strongest tempo in a 2 s window around each frame (grey), the same smoothed with a 2 s moving average (orange), the global estimate (dashed) and the detected beats (dotted).
As you can see, the instantaneous tempo varies, as in any real performance. But we are looking for the general tempo for the whole segment, so we calculate the average of all the values. The estimate is close to what a listener would say, but it is an average over a passage whose tempo moves, and a tempogram can as easily settle on half or double the felt tempo (the octave error), so it is a starting point for the ear, not a verdict.
Dig deeper: calculating the autocorrelation
The tempogram is built by autocorrelation: the onset curve is compared with a delayed copy of itself, and the delays at which the two match are the periods of the beat and its subdivisions. The same idea finds pitch. Autocorrelate the waveform itself, and the delay at which it best matches is the period of the fundamental, whose inverse is the frequency. Pitch and tempo are the same kind of thing, a periodicity, at different speeds: a tempo lies between about 0.5 and 5 cycles per second, a pitch between 20 and 20,000, which is what the From pulse to pitch app in time and rhythm demonstrated. Pitch trackers such as pYIN add a model for choosing between the candidate periods when several match, and give the pitch contours listed among the mid-level features above. Harmony is found the other way round, from the spectrum rather than from delays: the chromagram folds the spectrum into twelve pitch classes, and a key profile compares that distribution with templates for the major and minor keys, as the key estimate printed under the chromagram shows.
Pitch¶
To estimate the pitch of a tune, the key it is played in and the harmonies used, we can turn to the chromagram, which estimates how much energy falls on each of the twelve pitch classes.
Source
import matplotlib.pyplot as plt
plt.rcParams.update({
"font.size": 10,
"axes.titlesize": 11,
"axes.labelsize": 10,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"legend.fontsize": 9,
"figure.figsize": (10, 4),
"figure.dpi": 100,
"savefig.dpi": 150,
"axes.spines.top": False,
"axes.spines.right": False,
})
# Compute chromagram (CQT-based)
chroma = librosa.feature.chroma_cqt(y=y, sr=sr, hop_length=hop_length)
plt.figure(figsize=(10, 3.3))
librosa.display.specshow(chroma, y_axis='chroma', x_axis='time', sr=sr, hop_length=hop_length, cmap='magma')
plt.colorbar(label='Chroma energy')
plt.title('Chromagram (CQT)')
plt.tight_layout()
# show the plot and an audio playbar for the loaded file
plt.show()

Figure: Chromagram of the excerpt: the energy in each of the twelve pitch classes over time.
From the chromagram, we can see that most of its energy is centred around a tone corresponding to pitch class E. Remember that a chromagram (like a spectrogram) is a visualisation of a collection of numbers. Calculating the averages of each “strip” in the chromagram, we can get a numerical value for how much they are represented, and, as you can see below, the E turns up as the one with the highest chroma energy. Remember that this is not in itself a proof that the note E is the most prominent, but it is a good indication. The printed key estimate goes one step further: it correlates the mean chroma with the major and minor key profiles from harmony and melody, in every transposition, and reports the best match.
Source
import matplotlib.pyplot as plt
plt.rcParams.update({
"font.size": 10,
"axes.titlesize": 11,
"axes.labelsize": 10,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"legend.fontsize": 9,
"figure.figsize": (10, 4),
"figure.dpi": 100,
"savefig.dpi": 150,
"axes.spines.top": False,
"axes.spines.right": False,
})
pitch_names = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
chroma_mean = chroma.mean(axis=1)
mean_chroma = chroma_mean
# Key estimate: correlate the mean chroma with the Krumhansl and Kessler (1982) major and minor
# key profiles in all twelve transpositions and report the best match
major = np.array([6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88])
minor = np.array([6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17])
scores = {f"{pitch_names[k]} {mode}": float(np.corrcoef(mean_chroma, np.roll(profile, k))[0, 1])
for mode, profile in (("major", major), ("minor", minor)) for k in range(12)}
best = max(scores, key=scores.get)
print(f"Key estimate: {best} (correlation {scores[best]:.2f}; runner-up "
f"{sorted(scores, key=scores.get)[-2]} at {sorted(scores.values())[-2]:.2f})")
idx = int(np.argmax(mean_chroma))
prominent = pitch_names[idx]
prominence = float(mean_chroma[idx])
# simple bar plot highlighting the most prominent class
plt.figure(figsize=(10, 2.5))
bars = plt.bar(pitch_names, mean_chroma, color='C0')
bars[idx].set_color('C1')
plt.ylabel('Mean chroma energy')
plt.title('Mean chroma per pitch class - highlighted = most prominent')
plt.tight_layout()
plt.show()
Key estimate: E major (correlation 0.75; runner-up E minor at 0.65)

Figure: Mean chroma energy per pitch class over the whole excerpt, with the most prominent class highlighted.
Harmony¶
The chromagram can also help us to get information about the harmonic content of a tune. From the chromagram, we can see that the B also scores high. There are two reasons for this. First, from acoustics, you would expect a high level of energy in the fundamental frequency (E) and its first overtones (the first being the E one octave above, and the second the B).
The second explanation for the prominent B in the chromagram is the music arrangement: B is present in both the E minor and the E major chord, the bass vamp moves between E and B, and McCoy Tyner’s piano voicings are built in fourths around B, E and A rather than in thirds. The chromagram therefore sees B both as an overtone of E and as a note played in its own right. The printed key estimate agrees on E, and major and minor come out close because the arrangement alternates between the two.
Notice that the third-highest pitch class in the example above is D#. This can partly be explained harmonically: Coltrane’s arrangement alternates an E minor vamp with an E major one, and over the major chord the piano adds the major seventh, D#, which also appears in the melody there.
There is one more explanation for the D#, which relates to the feature extraction method: the chroma bins are a semitone wide and D# sits next to E, the strongest bin, so the vibrato and the slightly flat intonation of the soprano saxophone spill some of E’s energy into D#. Running the same analysis on the harmonic part of the signal alone gives the same ordering, so this is pitched energy, not percussion.
G and G# are the lowest of all, although they are the thirds of both E minor and E major and therefore the first notes a music theorist would write down. There are two reasons for this as well. First, the voicings in fourths leave the third out most of the time. Second, when a third is played the time is split between G, in the minor passages, and G#, in the major ones, so each gets about half of an already small share. The middle group, A, F# and D, are the fourth, the second and the seventh of E: the notes of the fourth-based voicings and of the melody.
What is important to take from all of this is that a chromagram measures energy per pitch class, not chord membership. It reflects the harmonic series and the voicings as much as the chord symbols, which is why a key read off a chromagram has to be taken with the same care as the tempo estimate above.
Source separation¶
In the example above, we examined the signal as one “chunk” of information. An alternative, and more advanced, approach is to begin by isolating individual instruments or voices from a mix, what is called source separation. Humans can do this easily: attend to one instrument in an ensemble or one voice in a crowd, as discussed in auditory scene analysis. For machines the problem is not solved, and is actively researched in the MIR community.
A simple type of source separation is to split the signal into two parts: harmonic and percussive.
Source
import matplotlib.pyplot as plt
plt.rcParams.update({
"font.size": 10,
"axes.titlesize": 11,
"axes.labelsize": 10,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"legend.fontsize": 9,
"figure.figsize": (10, 4),
"figure.dpi": 100,
"savefig.dpi": 150,
"axes.spines.top": False,
"axes.spines.right": False,
})
y_harmonic, y_percussive = librosa.effects.hpss(y)
fig, (ax_o, ax_hp) = plt.subplots(2, 1, figsize=(10, 5), sharex=True, sharey=True)
librosa.display.waveshow(y, sr=sr, ax=ax_o, color="0.4")
ax_o.set(title="Original waveform", ylabel="Amplitude", xlabel="")
librosa.display.waveshow(y_harmonic, sr=sr, ax=ax_hp, color="#1f77b4", alpha=0.9)
librosa.display.waveshow(y_percussive, sr=sr, ax=ax_hp, color="#d62728", alpha=0.7)
ax_hp.set(title="Harmonic and percussive components", ylabel="Amplitude", xlabel="Time (s)")
import matplotlib.patches as mpatches
ax_hp.legend(handles=[mpatches.Patch(color="#1f77b4", label="Harmonic"),
mpatches.Patch(color="#d62728", label="Percussive")], loc="upper right")
plt.tight_layout()
plt.show()
display(Audio(y_harmonic, rate=sr))
display(Audio(y_percussive, rate=sr))
Figure: The excerpt’s waveform (top) and its harmonic and percussive components after harmonic–percussive separation (bottom). The two components can be heard below.
Signal-processing methods like this are well understood and help us along the way, but are still far from extracting each instrument fully. Nowadays, the state-of-the-art separators are deep learning systems that have learned what voices, drums and bass sound like from large collections of recordings. Below is the result of using Demucs, an open-source neural network trained on studio multitracks to separate the Coltrane track into the six stem types it is trained on: drums, bass, vocals, guitar, piano, and everything else. You can see the result here and listen to each extracted stem:
Source
import os
import numpy as np
import librosa, librosa.display
from IPython.display import Audio, display
import matplotlib.pyplot as plt
if "y" not in globals(): # so that this cell also runs on its own
y, sr = librosa.load("audio/week6_audio_ex_2_coltrane_myfavthings.mp3", sr=22050, mono=True)
hop_length = 512
plt.rcParams.update({
"font.size": 10,
"axes.titlesize": 11,
"axes.labelsize": 10,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"legend.fontsize": 9,
"figure.figsize": (10, 4),
"figure.dpi": 100,
"savefig.dpi": 150,
"axes.spines.top": False,
"axes.spines.right": False,
})
stem_dir = "audio/coltrane_stems"
stems = ["drums", "bass", "piano", "other", "vocals", "guitar"]
fig, axes = plt.subplots(len(stems), 1, figsize=(10, 10), sharex=True)
for ax, name in zip(axes, stems):
y_s, sr_s = librosa.load(os.path.join(stem_dir, name + ".mp3"), sr=sr, mono=True)
S_s = librosa.amplitude_to_db(np.abs(librosa.stft(y_s, n_fft=2048, hop_length=hop_length)), ref=np.max(np.abs(librosa.stft(y, n_fft=2048, hop_length=hop_length))))
librosa.display.specshow(S_s, sr=sr, hop_length=hop_length, x_axis="time", y_axis="log", cmap="magma", ax=ax, vmin=-80, vmax=0)
rms = float(np.sqrt(np.mean(y_s ** 2)))
ax.set_ylabel(name)
ax.text(0.99, 0.9, f"RMS {20 * np.log10(rms + 1e-9):.0f} dB", transform=ax.transAxes, ha="right", va="top", fontsize=8, color="w")
ax.label_outer()
axes[0].set_title("Demucs (htdemucs_6s) stems of the Coltrane excerpt, log-frequency spectrograms on one colour scale")
axes[-1].set_xlabel("Time (s)")
plt.tight_layout()
plt.show()
for name in stems:
print(name)
display(Audio(os.path.join(stem_dir, name + ".mp3")))

drums
bass
piano
other
vocals
guitar
Figure: Log-frequency spectrograms of the six Demucs stems of the excerpt, on one colour scale, with a player for each stem below.
You can see/hear that the bass, piano and drum stems work quite well. The bass stem holds the E–B vamp, the piano stem the fourth-based voicings with B, E and A on top, and the drum stem the cymbals and brushes. The problem is that the Demucs model is not trained on saxophone sound, so the saxophone ends up in the “other” category with whatever else did not fit. The model extracts “vocals”, but since there are no vocals, that one is silent, and the “guitar” stem is also nearly silent, holding only some misclassified fragments of bass notes and piano chords. The lesson to learn from this is that a separator can only sort sound into the categories it was trained on.
To exemplify the importance of picking the right model, let us also investigate the result of another separator. BS-RoFormer, a transformer that works on frequency bands and currently scores highest on the standard benchmark, is trained to split a mix into vocals and everything else. Run on the excerpt, its vocals stem is empty, about 50 dB below the mix, and its instrumental stem is the mix:
Source
import os
import numpy as np
import librosa, librosa.display
from IPython.display import Audio, display
import matplotlib.pyplot as plt
if "y" not in globals(): # so that this cell also runs on its own
y, sr = librosa.load("audio/week6_audio_ex_2_coltrane_myfavthings.mp3", sr=22050, mono=True)
hop_length = 512
plt.rcParams.update({
"font.size": 10,
"axes.titlesize": 11,
"axes.labelsize": 10,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"legend.fontsize": 9,
"figure.figsize": (10, 4),
"figure.dpi": 100,
"savefig.dpi": 150,
"axes.spines.top": False,
"axes.spines.right": False,
})
ref = np.max(np.abs(librosa.stft(y, n_fft=2048, hop_length=hop_length)))
fig, axes = plt.subplots(2, 1, figsize=(10, 4.5), sharex=True)
for ax, name in zip(axes, ["roformer_vocals", "roformer_instrumental"]):
y_s, _ = librosa.load(f"audio/coltrane_roformer/{name}.mp3", sr=sr, mono=True)
S_s = librosa.amplitude_to_db(np.abs(librosa.stft(y_s, n_fft=2048, hop_length=hop_length)), ref=ref)
librosa.display.specshow(S_s, sr=sr, hop_length=hop_length, x_axis="time", y_axis="log", cmap="magma", ax=ax, vmin=-80, vmax=0)
rms = float(np.sqrt(np.mean(y_s ** 2)))
ax.set_ylabel(name.replace("roformer_", ""))
ax.text(0.99, 0.9, f"RMS {20 * np.log10(rms + 1e-9):.0f} dB", transform=ax.transAxes, ha="right", va="top", fontsize=8, color="w")
ax.label_outer()
axes[0].set_title("BS-RoFormer (vocals model) on the same excerpt, same colour scale as above")
axes[-1].set_xlabel("Time (s)")
plt.tight_layout()
plt.show()
for name in ["roformer_vocals", "roformer_instrumental"]:
print(name.replace("roformer_", ""))
display(Audio(f"audio/coltrane_roformer/{name}.mp3"))

vocals
instrumental
Figure: Log-frequency spectrograms of the two BS-RoFormer stems of the excerpt, vocals and instrumental, on the same colour scale as the Demucs figure.
The model might have mistaken the saxophone for a voice, but it did not, which is correct. It is nevertheless useless on this music. BS-RoFormer works well for karaoke tracks, separating the voice from the rest, and fails on most other things.
Event detection¶
Stem separation can be seen as a way of segmenting the sound “vertically”. Now, let us consider also “horizontal” segmentation, what is often called event detection: onsets, beats, the start of a chorus. This is the machine’s version of the grouping problem posed in psychoacoustics: which parts of a continuous signal belong together? While the auditory system handles event detection effortlessly, it is not at all straightforward for machines.
One classic method for event detection compares the recording with itself in a self-similarity matrix:
Source
import matplotlib.pyplot as plt
plt.rcParams.update({
"font.size": 10,
"axes.titlesize": 11,
"axes.labelsize": 10,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"legend.fontsize": 9,
"figure.figsize": (10, 4),
"figure.dpi": 100,
"savefig.dpi": 150,
"axes.spines.top": False,
"axes.spines.right": False,
})
# Compute and plot a self-similarity matrix using chroma frame features
X_feat = chroma.T # shape: (n_frames, n_pitches)
# L2-normalize frame vectors (avoid division by zero)
norms = np.linalg.norm(X_feat, axis=1, keepdims=True)
norms[norms == 0] = 1.0
Xn = X_feat / norms
# Cosine self-similarity (frames x frames)
ssm = np.dot(Xn, Xn.T)
# Plot the self-similarity matrix mapped to time (uses `times` array already in the notebook)
plt.figure(figsize=(10, 6))
extent = [times[0], times[-1], times[0], times[-1]] # map indices to seconds
plt.imshow(ssm, origin='lower', aspect='auto', cmap='magma', extent=extent, vmin=0, vmax=1)
plt.xlabel('Time (s)')
plt.ylabel('Time (s)')
plt.title('Self-similarity matrix (cosine) - chroma/frame features')
# Optionally overlay beat times if available
if 'beat_times' in globals():
for bt in beat_times:
plt.axvline(bt, color='w', linestyle='--', linewidth=0.5, alpha=0.3)
plt.axhline(bt, color='w', linestyle='--', linewidth=0.5, alpha=0.3)
plt.tight_layout()
plt.show()

Figure: Self-similarity matrix of the excerpt from chroma features: each point shows how similar two moments are, with the diagonal as the reference and repeated passages as stripes parallel to it. Beat times are overlaid as faint lines.
You can see how repeated sections appear as “stripes” in the matrix, which can be used to look for similarity. From there the machine can mark the change points and group the frames into parts:
Source
import matplotlib.pyplot as plt
plt.rcParams.update({
"font.size": 10,
"axes.titlesize": 11,
"axes.labelsize": 10,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"legend.fontsize": 9,
"figure.figsize": (10, 4),
"figure.dpi": 100,
"savefig.dpi": 150,
"axes.spines.top": False,
"axes.spines.right": False,
})
chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
bounds = librosa.segment.agglomerative(chroma, 20)
bound_times = librosa.frames_to_time(bounds, sr=sr)
import matplotlib.transforms as mpt
fig, ax = plt.subplots(figsize=(10, 3.3))
trans = mpt.blended_transform_factory(
ax.transData, ax.transAxes)
librosa.display.specshow(chroma, y_axis='chroma', x_axis='time', ax=ax)
ax.vlines(bound_times, 0, 1, color='linen', linestyle='--',
linewidth=2, alpha=0.9, label='Segment boundaries',
transform=trans)
ax.legend()
ax.set(title='Chromagram with segment boundaries')
plt.tight_layout()
plt.show()
Figure: The chromagram of the excerpt with the segment boundaries found from the self-similarity matrix drawn as vertical lines.
Comparing the parts to describe the musical form takes more code and more judgement, so we will not continue with that here. What is important to understand is that machine listening gives fast, consistent and reproducible descriptions of acoustic properties. But it does not give musical interpretation. So you always need to check that what the machine suggests makes sense.
Machine learning¶
So far, we have only asked the machine to extract features and describe them. It can also try to answer: is this a trumpet, which genre, which song, will this listener like it? These are the classic tasks of MIR:
Classification and recognition: which instrument, which genre, speech or music. The pitfalls are biased datasets and instruments that sound alike.
Recommendation: audio features combined with listening behaviour. Useful for discovery, prone to bias, and hungry for personal data.
Transcription: audio into notes. Single melodies work well; full polyphonic transcription does not yet.
Structure analysis: verses, choruses, boundaries. “Meaningful” is subjective, so evaluation needs human judgement.
Search by description: “find tracks with a trumpet solo”. The hard part is mapping everyday words to reliable labels.
Mood and emotion: estimating how music feels. This is where MIR meets the music psychology of physiology, with all the individual and cultural differences that chapter described.
From rules to learning¶
Traditional MIR systems were rule-based, sometimes also referred to as expert systems. They rely on specifying various rules as algorithms using thresholds, peak picking, and different types of decision rules. Such systems are small, fast, easy to understand and easy to tune, but they do not scale well and break when the music is unlike what they were tuned on.
The AI revolution is based on the capacities of learning-based systems, which find their own patterns in data. When trained on enough data, they have proven to be more accurate and capable of solving also tasks they were not trained on. However, the downside is that they need to be trained on lots of data and require large computational resources. Also, they effectively function as a “black box”, meaning that it is impossible to know what they actually “think”. We use quotation marks here, since even though the machine may appear to think, machine learning is only fancy statistics.
Artificial neural networks¶
Most learning-based systems are built from artificial neural networks (ANNs). Recall that we mentioned this when discussing the brain. Artificial neural networks were developed from the 1950s, inspired by the human brain. Such a network is made of simple units arranged in layers. Each unit multiplies its inputs by weights, adds them up, passes the sum through a simple non-linear function, and hands the result to the next layer.
A simple artificial neural network: an input layer, one hidden layer and an output layer, each unit connected to every unit in the next layer by a weight.
Training means showing the network many examples, measuring how wrong its output is, and adjusting every weight a little towards being less wrong. By repeating this thousands, or even millions of times, the network “learns”.
Deep learning is also based on artificial neural networks, but includes many more layers, which is why it is called “deep”. The idea is that early layers pick up local detail (a transient, a spectral edge) and later layers combine it into something abstract (a timbre, a chord, a genre).
What is important to understand is that the features emerging from such a network are not chosen by a person, and may not even be easily explained. Also, as we saw in the example above, what the network is trained on influences what it can find. If it is not trained to classify saxophone sounds, it will not find them by itself.
Dig deeper: model families
There are many different types of models. These are some of the more well-known model families:
Hidden Markov Models (HMMs) describe a signal as moving between a small set of hidden states, such as notes or chords, and estimate the most likely state sequence. They are lightweight and work with little data, but struggle when musical patterns stretch over long spans.
Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM) networks process a sequence one step at a time, with LSTMs adding an internal memory for longer context. They handle moderate musical context well but are slower than models that process a whole sequence at once.
Temporal or dilated convolutional networks (temporal CNNs, TCNs) apply the pattern-matching filters of a convolutional neural network along the time axis, with deeper layers seeing longer stretches of signal. They compute efficiently and suit low-latency streaming, but the amount of context they see is fixed by the design.
Transformers and attention-based models let every moment in a sequence relate directly to every other, which suits long-range structure and tasks such as transcription and form analysis. They often give the best results but demand far more computation and memory, especially for long recordings.
Real time or offline¶
AI-based systems can be rule-based or learning-based (or hybrid), but they can also differ in terms of how they operate in time. Most systems work in non-real-time, and are often referred to as offline systems. Think of regular chatbots and other systems where you type in something and then get a result. They can be quite fast, but you never know exactly when the reply comes. This is fine for many use cases, including music analysis. Then, the system can look ahead, revise earlier decisions and run expensive smoothing, which is why transcription and structural analysis are done offline. Musical structure is easiest to find after the fact.
For music performance, however, one needs a system that can respond in real time while the music plays, as in live accompaniment or an interactive installation. It hears only what has arrived and has a few tens of milliseconds to decide. Latency, the delay of a signal, is critical for such systems, and algorithms are typically developed to be simple and quick. A rapid response time is usually more important than the quality of the answer.
Dig deeper: where the latency comes from
Latency ≈ window duration + model lookahead + processing time. With n_fft=2048 at sr=22050, the analysis window alone is ≈ 92.9 ms, and a hop_length of 512 advances in 23.2 ms steps, so even before any model runs, the system is already that far behind the sound.
Real-time work therefore requires causal algorithms (causal filters, causal convolutions, stateful RNNs/TCNs, or streaming transformers with limited lookahead), a streaming frontend with short windows and small hops, cheap incremental features (onset strength, low-band log-mel, incremental CQT), and simple online post-processing (peak picking, adaptive thresholds). Compute has to be bounded and predictable to meet deployment constraints (CPU/GPU, battery, I/O), which in practice means lightweight models or hybrid pipelines with a rule-based front end and a small learned model.
Offline systems can instead use larger windows, global context, and bidirectional models (bi-RNNs, full attention), plus expensive post-processing (Viterbi smoothing, global segmentation, search) and whole-track normalisation.
Generative music AI¶
We have so far focused on analytical machine listening systems, extracting information from music that already exists, or deciding something about it. Generative music AI turns the pipeline around and produces new music Briot et al., 2020. The two are related: a system can only generate convincingly in a style it has learned to represent, and generative models reuse the model families described above.
Generation comes in two kinds. Symbolic or score-based generation works with notes: it produces notation or MIDI that a musician or a synthesiser then plays. Audio-based generation skips the score and produces the waveform directly. Some people think this can only work on big servers, but the three examples below were all made on a laptop with open-source software.
Score-based generation: a Markov tune¶
The oldest generative model is also the simplest. A Markov chain reads a tune note by note and counts how often each note follows the few notes before it. Hiller and Isaacson used such chains for the fourth movement of the Illiac Suite in 1957, the first substantial piece composed with a computer Hiller & Isaacson, 1959.
The example below learns from a few hundred German folk songs in the Essen Folksong Collection Schaffrath, 1995, which ships with the music21 library. Each tune is first transposed to C major, so that the chain learns scale degrees rather than absolute pitches. The chain then counts, for every pair of consecutive notes, which note with which duration came next. Then, the generator walks through those counts: start as a tune in the collection starts, draw each next note in proportion to how often it followed the previous two, refuse any duration that would cross a barline, and stop after eight bars on the tonic. The result is rendered as notation with LilyPond and played with a plain synthetic tone:
Source
import os, random, subprocess
from collections import Counter, defaultdict
import numpy as np
from IPython.display import Audio, display
from music21 import corpus, interval, pitch
# 1. Learn: the major-mode tunes of one Essen collection (Boehme's German folk songs), transposed to C major
opus = corpus.parse("essenFolksong/boehme10")
DURATIONS = {4.0: "1", 3.0: "2.", 2.0: "2", 1.5: "4.", 1.0: "4", 0.75: "8.", 0.5: "8", 0.25: "16"}
tunes = []
for s in opus.scores:
k = s.analyze("key")
if k.mode != "major":
continue
semis = interval.Interval(k.tonic, pitch.Pitch("C4")).semitones % 12
shift = interval.Interval(semis if semis <= 6 else semis - 12)
events = [(n.pitch.transpose(shift).midi, float(n.quarterLength))
for n in s.parts[0].flatten().notes if n.isNote and float(n.quarterLength) in DURATIONS]
if len(events) > 8:
tunes.append(events)
ORDER = 2 # how many previous notes the chain remembers
table = defaultdict(Counter) # (previous notes) -> Counter of next (pitch, duration)
starts = []
for ev in tunes:
starts.append(tuple(ev[:ORDER]))
for j in range(ORDER, len(ev)):
table[tuple(ev[j - ORDER:j])][ev[j]] += 1
print(f"Learned from {len(tunes)} major-mode tunes: {len(table)} contexts, "
f"{sum(sum(c.values()) for c in table.values())} transitions.")
# 2. Generate eight bars of 4/4 that end on the tonic; a note may not cross a barline
def generate(seed, bars=8):
rng = random.Random(seed)
while True:
out = list(rng.choice(starts))
pos = sum(d for _, d in out)
while pos < bars * 4:
room = 4 - (pos % 4)
options = [(e, w) for e, w in table.get(tuple(out[-ORDER:]), {}).items() if e[1] <= room]
if not options:
break
e = rng.choices([e for e, _ in options], weights=[w for _, w in options])[0]
out.append(e)
pos += e[1]
if pos == bars * 4 and out[-1][0] % 12 == 0:
return out
tune = generate(seed=3)
print(f"Generated {len(tune)} notes.")
# 3. Notation with LilyPond (the book's notation renderer)
NAMES = ["c", "cis", "d", "dis", "e", "f", "fis", "g", "gis", "a", "ais", "b"]
def ly(m):
octave = m // 12 - 4
return NAMES[m % 12] + ("'" * octave if octave > 0 else "," * -octave)
notes = " ".join(ly(m) + DURATIONS[d] for m, d in tune)
folder = "figures/machine-listening/notation"
os.makedirs(folder, exist_ok=True)
with open(f"{folder}/markov-tune.ly", "w") as f:
f.write('\\include "../../notation/common.ily"\n'
'% Written by the Markov tune cell in machine-listening.ipynb; do not edit by hand.\n'
'\\score { \\new Staff { \\clef treble \\key c \\major \\time 4/4 ' + notes + ' \\bar "|." } }\n')
try: # the SVG is shown by the image directive in the next cell
subprocess.run(["bash", "figures/notation/render.sh", folder], check=True, capture_output=True)
except Exception:
print("LilyPond is not available; the tune in LilyPond notation:", notes)
# 4. A plain tone for each note: four harmonics with an exponential decay, 100 beats per minute
sr, beat = 16000, 60 / 100
audio = []
for m, d in tune:
t = np.arange(int(d * beat * sr)) / sr
f0 = 440 * 2 ** ((m - 69) / 12)
tone = sum(np.sin(2 * np.pi * f0 * h * t) / h for h in range(1, 5)) * np.exp(-3 * t / (d * beat))
audio.append(tone)
audio = np.concatenate(audio)
display(Audio(audio / np.abs(audio).max(), rate=sr))
Learned from 354 major-mode tunes: 2663 contexts, 19953 transitions.
Generated 54 notes.
Figure: The tune written by the Markov chain above, eight bars in C major.
When analysing it, you can see that the tune is plausible: every pair of notes is followed by the third somewhere in the collection. So the steps, leaps and rhythms are those of the style. What it lacks is everything that spans more than three notes: phrases that return, a cadence halfway through, a shape that goes somewhere. A chain with a longer memory would copy longer fragments of the tunes it learned from, not invent new phrases. This is the gap that neural networks close.
FolkRNN solves the same prediction task as the Markov chain, but with a recurrent network whose state carries information about the whole tune so far, trained on tens of thousands of transcriptions. The large language models behind today’s chat systems predict the next token in the same way. Run the cell again with another seed and the chain writes another tune; it has no preference among them, and the choice of which to keep is the composer’s.
Audio-based generation: text to music¶
Audio-based generation systems produce the waveform directly. Research systems such as MusicLM and MusicGen showed that a written prompt like “upbeat funk with slap bass” could become sound, and commercial services such as Suno and Udio now deliver complete songs with vocals from a sentence of text.
MusicGen Copet et al., 2023 is one of the few such systems with open weights, so it can run on a laptop. It does not predict samples: a neural audio codec first turns sound into a stream of discrete tokens, a few tens per second, and a transformer, the model family behind language models, predicts the next tokens given the previous ones and a text prompt. The small model has about 300 million weights, which sounds like a lot, but the clips below took only seconds to generate on a laptop’s graphics card. The first clip comes from the prompt alone. The second uses the melody variant of the model, which also takes a chromagram, here of the first 15 s of the Coltrane excerpt we have analysed above, as a condition, with the prompt asking for a string quartet.
Source
import json
import numpy as np
import librosa, librosa.display
import matplotlib.pyplot as plt
from IPython.display import Audio, display
plt.rcParams.update({"font.size": 10, "axes.titlesize": 11, "axes.labelsize": 10, "xtick.labelsize": 9, "ytick.labelsize": 9,
"figure.dpi": 100, "savefig.dpi": 150, "axes.spines.top": False, "axes.spines.right": False})
meta = json.load(open("audio/musicgen/meta.json"))
clips = [("text_funk", f'MusicGen small, prompt: "{meta["text_funk"]["prompt"]}"'),
("melody_input", "Melody condition: the Coltrane excerpt, first 15 s"),
("melody_coltrane", f'MusicGen melody, prompt: "{meta["melody_coltrane"]["prompt"]}"')]
PCS = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
fig, axes = plt.subplots(len(clips), 1, figsize=(10, 7.5), sharex=True)
for ax, (name, title) in zip(axes, clips):
y, sr = librosa.load(f"audio/musicgen/{name}.mp3", sr=22050, mono=True)
S = librosa.amplitude_to_db(np.abs(librosa.stft(y, n_fft=2048, hop_length=512)), ref=np.max)
librosa.display.specshow(S, sr=sr, hop_length=512, x_axis="time", y_axis="log", cmap="magma", ax=ax, vmin=-80, vmax=0)
ax.set_title(title, loc="left")
ax.label_outer()
chroma = librosa.feature.chroma_cqt(y=y, sr=sr).mean(axis=1)
tempo = float(librosa.feature.tempo(y=y, sr=sr)[0])
top = ", ".join(PCS[k] for k in np.argsort(chroma)[::-1][:3])
print(f"{name:16s} strongest pitch classes {top:12s} tempo estimate {tempo:.0f} BPM"
+ (f" generated in {meta[name]['generation_s']} s" if name in meta else ""))
axes[-1].set_xlabel("Time (s)")
plt.tight_layout()
plt.show()
for name, title in clips:
print(title)
display(Audio(f"audio/musicgen/{name}.mp3"))
text_funk strongest pitch classes E, F#, A tempo estimate 112 BPM generated in 11.8 s
melody_input strongest pitch classes E, D#, B tempo estimate 161 BPM
melody_coltrane strongest pitch classes E, B, A tempo estimate 129 BPM generated in 48.4 s

MusicGen small, prompt: "upbeat funk with slap bass, drums and electric piano"
Melody condition: the Coltrane excerpt, first 15 s
MusicGen melody, prompt: "string quartet, chamber music, slow and lyrical"
Figure: Log-frequency spectrograms of the text-prompted MusicGen clip (top), the first 15 s of the Coltrane excerpt used as the melody condition (middle) and the melody-conditioned clip (bottom), with players for each.
Timbre transfer with RAVE¶
A third example does not start from a prompt at all. RAVE Caillon & Esling, 2021, developed at IRCAM, is an autoencoder. An encoder network compresses audio into a handful of numbers per frame, a latent representation, and a decoder network reconstructs audio from them.
Trained on one kind of sound, the decoder can only produce that kind of sound. Feed the encoder something else, however, and the decoder renders it in the timbre it knows. This can be seen as a form of “timbre transfer”. RAVE runs faster than real time on a laptop, which is why it has become popular in live performance, where a performer’s voice or instrument can be re-rendered on stage.
Below, the first 30 s of the Coltrane excerpt pass through two pretrained models from IRCAM, one trained on 80 hours of vintage recordings and one on 8 hours of percussion. The printed line reports how closely each output’s loudness contour follows the input’s, after allowing for the model’s own delay:
Source
import json
import numpy as np
import librosa, librosa.display
import matplotlib.pyplot as plt
from IPython.display import Audio, display
plt.rcParams.update({"font.size": 10, "axes.titlesize": 11, "axes.labelsize": 10, "xtick.labelsize": 9, "ytick.labelsize": 9,
"figure.dpi": 100, "savefig.dpi": 150, "axes.spines.top": False, "axes.spines.right": False})
meta = json.load(open("audio/rave/meta.json"))
sr, hop = 22050, 512
y_in, _ = librosa.load("audio/week6_audio_ex_2_coltrane_myfavthings.mp3", sr=sr, mono=True, duration=meta["vintage"]["seconds"])
env_in = librosa.feature.rms(y=y_in, hop_length=hop)[0]
rows = [("input", y_in, "Input: the Coltrane excerpt, first 30 s")] # audio/rave/input.mp3 is the same 30 s, for the player
for name in ["vintage", "percussion"]:
y, _ = librosa.load(f"audio/rave/{name}.mp3", sr=sr, mono=True)
rows.append((name, y, f"RAVE '{name}' model ({meta[name]['latent_dims']} latent dimensions, "
f"{meta[name]['latent_rate_hz']:.0f} frames per second, processed in {meta[name]['generation_s']} s)"))
env = librosa.feature.rms(y=y, hop_length=hop)[0][: len(env_in)]
n = min(len(env), len(env_in))
corr, lag = max((np.corrcoef(env_in[: n - l], env[l:n])[0, 1], l) for l in range(0, 60))
print(f"{name:11s} loudness contour follows the input with correlation {corr:.2f} after a delay of {lag * hop / sr:.2f} s")
fig, axes = plt.subplots(len(rows), 1, figsize=(10, 7.5), sharex=True)
for ax, (name, y, title) in zip(axes, rows):
S = librosa.amplitude_to_db(np.abs(librosa.stft(y, n_fft=2048, hop_length=hop)), ref=np.max)
librosa.display.specshow(S, sr=sr, hop_length=hop, x_axis="time", y_axis="log", cmap="magma", ax=ax, vmin=-80, vmax=0)
ax.set_title(title, loc="left")
ax.label_outer()
axes[-1].set_xlabel("Time (s)")
plt.tight_layout()
plt.show()
for name, y, title in rows:
print(title)
display(Audio(f"audio/rave/{name}.mp3"))
vintage loudness contour follows the input with correlation 0.85 after a delay of 0.60 s
percussion loudness contour follows the input with correlation 0.77 after a delay of 0.05 s

Input: the Coltrane excerpt, first 30 s
RAVE 'vintage' model (16 latent dimensions, 23 frames per second, processed in 0.9 s)
RAVE 'percussion' model (4 latent dimensions, 22 frames per second, processed in 0.2 s)
Figure: Log-frequency spectrograms of the first 30 s of the excerpt (top) and of its passage through the RAVE vintage model (middle) and percussion model (bottom), with players for each.
The percussion model keeps the rhythm of the quartet and replaces every sound in it with a drum, because drums are all it can make. The vintage model keeps more of the pitch content and adds the surface noise and band-limited tone of old records. Neither model was told anything about jazz; what you hear is the training set playing through the input.
Remember that such systems do not actually know anything about music. They are based on processing huge collections of music and then adjusting their weights until they can predict how such music tends to continue. When prompted, they assemble new output that follows the statistical patterns they have absorbed. They do not replay any single piece from the training set and usually also produce new results each time they are triggered.
While such systems have proven to be very powerful, many of them are also based on learning from copyrighted music without asking for permission or paying the artists Sturm et al., 2019. In 2024 major record labels took leading text-to-music services to court over the use of their catalogues, and that litigation is still running.
There is a cultural worry too: models trained mostly on commercially successful Western repertoire will also produce outputs that pull in the same direction. The result is a flood of generated similar-sounding music.
Today these systems are good at pastiche. They are good at generating a plausible 30-second lo-fi beat or a jingle in the style of 1980s synth-pop. They are much weaker when it comes to generating long-range form and breaking rules in the way that makes human-made music interesting. One can therefore think of them as idea-generating tools rather than as replacements.
Data and ethics¶
Every system in this chapter was shaped by the music it learned from. This section asks what that music was, what other data are added to it, and what the choice of data means for the people whose music and listening it contains.
Music data¶
For decades, MIR researchers worked mostly with symbolic data, primarily MIDI and MusicXML files. Most research now works with audio, which carries no symbols at all.
In addition to the data itself (MIDI, audio, etc.), we also have different types of metadata (artist, album, etc.), paradata (how it was recorded or analysed) and user data (who listened, and when). These supplementary data types give the music data its context.
Collecting diverse music data, metadata, paradata, and user data while respecting copyright, performers’ rights and privacy is one of the field’s standing problems. Researchers therefore lean on openly licensed recordings and documented datasets, and share down-sampled features or spectrograms when the audio itself cannot be shared.
Combining data types¶
Many systems add other data to the audio: lyrics to settle a mood, a score for exact pitches, video for the performer’s gestures. The MIR literature calls this multimodal MIR, borrowing the word that vision uses for perception through several senses. This book keeps multimodal for perception and speaks of data types here: a score and a recording are two kinds of data about one piece, not two senses.
A core challenge when working with several data types is to synchronise them: audio, scores, lyrics and video run on different clocks and must be aligned before they can be compared. The second challenge is comparison between kinds of data, which many systems solve with embeddings: lists of numbers from a trained model that place similar items, whether clips, lyric lines or images, close together.
Ethics¶
As mentioned above, the datasets and the models built on them have social consequences. Field recordings, concerts and classroom sessions contain identifiable voices, so consent, licences and known limitations belong with every dataset. Training data skewed by genre, language, recording quality or Western labels give models that fail silently on the music they never saw, and since perception and meaning are culturally conditioned, a model trained on a narrow corpus misrepresents the practices outside it. The generative systems above add unresolved questions of artist consent, credit and compensation.
The same problem can be found when working with people’s data. There are huge potentials in using interactive music systems in health and well-being settings. However, information about people’s bodies and minds can be misused. Music-based therapy tools must be validated in proper trials before any benefit is claimed, as the music-therapy section of the brain showed.
Training large models also consumes large amounts of energy, so one should always keep the method proportionate to the question. And, for all sorts of work, one should be transparent about how AI-based tools are used.
Dig deeper: tools, datasets, and services
A few names you will meet in the literature and in practice; none of them is required for this course.
Open-source libraries
librosa: A lightweight, high-level Python library for audio analysis and feature extraction (spectrograms, chroma, MFCCs, tempograms). Good for prototyping and education. (pip install librosa)
Essentia: C++ DSP library with Python bindings: very large feature set, audio descriptors, and production-grade implementations of many MIR algorithms (beat, onset, pitch, timbre). Useful when performance and completeness matter.
madmom: Focused on MIR tasks such as beat tracking, onset detection, and tempo estimation with efficient Cython code and pretrained models. Good for beat/onset pipelines and real-time algorithms.
Spleeter (Deezer): Fast, easy-to-use source separation (2/4/5 stems) with pretrained U-Net models. Suited to quick vocal/instrument separation and dataset preparation.
Open-Unmix (UMX): Open, research-oriented music source separation model (frequency-domain, PyTorch) and evaluation scripts (museval). Good for reproducible separation experiments.
Demucs: Time-domain neural separator (waveform) that often yields strong perceptual quality for music separation. Useful as a modern baseline for source separation work.
BS-RoFormer and Mel-Band RoFormer: Transformer-based separators from ByteDance (2023) with open weights that now score above Demucs on the standard benchmark, especially for vocals; the usual way to run them, together with Demucs and the MDX-Net models, is the maintained command-line wrapper audio-separator.
CREPE: A convolutional model for pitch/F0 estimation directly from waveform. Provides frame-level pitch estimates and confidence measures.
Onsets & Frames (Magenta): Neural system for piano transcription (onset detection + framewise prediction + decoding). Good example of end-to-end transcription pipelines.
mir_eval / museval: Lightweight toolkits for standard MIR evaluation metrics. Use these for consistent, comparable results.
JAMS: JSON-based format and Python tools for storing and exchanging musical annotations (beats, chords, segments). Useful for reproducible annotation workflows.
Datasets and benchmarks
MUSDB18: Standard dataset for music source separation (stereo mixtures + stems).
MAESTRO: Aligned piano audio + MIDI dataset used for transcription and generation.
GTZAN / Million Song Dataset: Popular collections for genre / large-scale analysis (beware of known issues and biases).
Commercial services
Shazam: A consumer-facing music recognition service that identifies songs from short audio clips and returns metadata (title, artist, album) and listening links. Widely integrated into iOS/Android and many commercial platforms.
ACRCloud: Commercial audio fingerprinting and automatic content recognition (ACR) for music identification, broadcast monitoring, copyright compliance, and synchronised second-screen experiences. Offers cloud APIs and on-device SDKs for streaming, broadcasting, and automotive use cases.
Gracenote: Metadata and music-recognition services powering search, recommendation, and interactive media features for streaming platforms, consumer electronics, and infotainment systems. Commonly used to enrich catalogues and enable content discovery.
Audible Magic: Content identification and rights management platform specialising in copyright compliance, fingerprinting, and monetisation for user-generated and professional video/audio content. Used by platforms that need automated rights enforcement and revenue attribution.
Samba TV: A television analytics company that uses automatic content recognition (ACR) to identify what is playing on screen, powering audience measurement, personalised advertising, and interactive TV experiences.
A critical look: does all music sound the same these days?¶
In 2012, a MIR study made the headlines: pop music was getting louder and more alike. The evidence came from audio features computed over hundreds of thousands of recordings.
The claim is that popular music has become louder and less varied over the decades, in melody, harmony, and timbre.
The evidence is mixed. An analysis of nearly half a million tracks from 1955 to 2010 found that loudness rose steadily, that the range of timbres in use narrowed, and that transitions between pitches became more restricted over time Serrà et al., 2012. However, a later study of 17,000 songs from the US charts, 1960 to 2010, described the same period differently: it found no steady decline in diversity but three stylistic revolutions, in 1964, 1983, and 1991, with a dip in diversity in the mid-1980s, when drum machines and synthesisers dominated, followed by a recovery as hip-hop arrived Mauch et al., 2015.
The method is the same in both studies: chroma, timbre, and loudness features extracted from audio and tracked over time. So the disagreement comes from elsewhere: which recordings were included, which features were chosen, and what diversity is taken to mean. Each of those is a decision made by the analyst.
The limits apply to any such claim. Descriptors are proxies for musical qualities, not the qualities themselves. Datasets over-represent charts and Western pop. And the sample of old music we compare against has been filtered by decades of forgetting, so the past always sounds more varied than it was.
One part of the claim holds and can be measured: recordings have become louder. The rest, that music got worse, is not something a feature extractor can answer. Machine listening can tell you what changed in the audio; whether the change is a loss is a judgement the perceiver still has to make.
Dig deeper: what the machine takes from each chapter
A revision table: what each chapter taught, what the machine does with it, and the app to try.
| Chapter | What you learned | What the machine does with it | Where to try it |
|---|---|---|---|
| Tuning in | The four levels of description; music as a multimodal experience | Works in the digital representation and reaches up towards perception | |
| Listening | Modes of listening; the sound object; the soundscape | Must be told what to listen for; soundscape tools turn the attention around | Live spectrogram |
| Acoustics | Waveform, spectrum, the Fourier transform; signal and noise | The spectrogram is the front end of every pipeline | Window explorer |
| Electroacoustics | Microphones, sampling, latency | Audio input; sampling rate and window length set the latency | Sampling and quantisation |
| Psychoacoustics | Loudness, masking, auditory scene analysis | Perceptual scales inside the features; source separation; segmentation | Streaming lab |
| Time and rhythm | Pulse, metre, tempo, microtiming, entrainment | Onset detection, the tempogram, beat tracking, the octave error | Tap sync, Drum machine |
| Harmony and melody | Pitch class, key, expectation, streams | The chromagram, key finding, melody prediction, FolkRNN | Scale explorer, Chord lab, Melody lab |
| The body | Motion capture, video analysis, motiongrams | The same pipeline on video: frame differencing, self-similarity, pose estimation | Video visualiser, Video scrubber |
| Physiology | Heart, breath and skin as signals | The same pipeline on body signals: filter, detect, count | Camera pulse, Breathing monitor |
| Vision | Auditory–visual integration, gaze, the pupil | Combining data types; eye tracking as machine seeing | Eye tracker |
| The brain | Neurons, expectation, plasticity, brain imaging; the consumer headband | Artificial neural networks; the same pipeline on EEG: filter, band power, detect, average | Muse live (a program, not a web app) |
- Müller, M. (2021). Fundamentals of Music Processing: Using Python and Jupyter Notebooks. Springer International Publishing. 10.1007/978-3-030-69808-9
- McFee, B., Raffel, C., Liang, D., Ellis, D., McVicar, M., Battenberg, E., & Nieto, O. (2015). librosa: Audio and Music Signal Analysis in Python. Proceedings of the 14th Python in Science Conference, 18–24. 10.25080/Majora-7b98e3ed-003
- Briot, J.-P., Hadjeres, G., & Pachet, F.-D. (2020). Deep Learning Techniques for Music Generation. Springer International Publishing. 10.1007/978-3-319-70163-9
- Hiller, L. A., & Isaacson, L. M. (1959). Experimental Music: Composition with an Electronic Computer. McGraw-Hill.
- Schaffrath, H. (1995). The Essen Folksong Collection. In D. Huron (Ed.), Database containing 6,255 folksong transcriptions in the Kern format and a 34-page research guide. Center for Computer Assisted Research in the Humanities.
- Copet, J., Kreuk, F., Gat, I., Remez, T., Kant, D., Synnaeve, G., Adi, Y., & Défossez, A. (2023). Simple and Controllable Music Generation. Advances in Neural Information Processing Systems 36 (NeurIPS 2023). https://arxiv.org/abs/2306.05284
- Caillon, A., & Esling, P. (2021). RAVE: A Variational Autoencoder for Fast and High-Quality Neural Audio Synthesis. arXiv Preprint arXiv:2111.05011. 10.48550/arXiv.2111.05011
- Sturm, B. L. T., Iglesias, M., Ben-Tal, O., Miron, M., & Gómez, E. (2019). Artificial Intelligence and Music: Open Questions of Copyright Law and Engineering Praxis. Arts, 8(3), 115. 10.3390/arts8030115
- Serrà, J., Corral, Á., Boguñá, M., Haro, M., & Arcos, J. Ll. (2012). Measuring the Evolution of Contemporary Western Popular Music. Scientific Reports, 2, 521. 10.1038/srep00521
- Mauch, M., MacCallum, R. M., Levy, M., & Leroi, A. M. (2015). The Evolution of Popular Music: USA 1960–2010. Royal Society Open Science, 2(5), 150081. 10.1098/rsos.150081
- Lerch, A. (2022). An Introduction to Audio Content Analysis: Music Information Retrieval Tasks and Applications. Wiley. 10.1002/9781119890980