By Tania Alwan
An AI song extender takes a track that ends too soon and makes it longer. That sounds like one feature, but there are two very different ways to do it: generate new audio that continues the song, or rearrange audio that already exists so the song plays for longer.
In this post we look at both approaches, then build a tiny loop-based extender in Python with NumPy only: chroma features, a self-similarity search to find where the song can jump, and a crossfade to hide the seam. The example is a toy, but it shows the ideas behind the "extend" button.
Two ways to build an AI song extender
1. Generative continuation. A music model receives the end of the existing audio as a prompt and generates what comes next. Meta's open-source MusicGen, in the AudioCraft library, exposes this directly as a generate_continuation method in its generation API, which takes a batch of waveforms "used for continuation" plus optional text descriptions. Consumer apps wrap the same idea in a button: Suno's help centre describes an Extend feature where you choose how much of the original to keep, add new lyrics or style details, and then stitch the new ending onto the original.
The strength is genuinely new material: a new verse, a different ending. The risk is drift, because the model only "sees" a limited window of audio and has to guess what should come next.
2. Loop-based extension. Instead of generating anything, the extender finds places where the song is similar to itself and jumps between them, so a chorus can repeat or a section can loop seamlessly. This relies on a self-similarity matrix: describe each slice of audio as a feature vector, compare every slice with every other, and repeated sections show up as high-similarity diagonals.
The strength is that every note is real audio from the original. The limit is that nothing new is created; you only get more of what was already there.
The ingredients of a loop-based extender
Three building blocks do most of the work:
- Chroma features. A chroma vector folds spectral energy into the 12 pitch classes (C, C#, D and so on), so it captures harmony while ignoring octave and, to a degree, instrumentation.
- Cosine similarity. With normalised vectors, the dot product is the cosine similarity: 1.0 means the same harmonic content, lower values mean less alike.
- Crossfades. Cutting from one waveform to another at an arbitrary point creates a discontinuity you hear as a click. A short crossfade blends the two signals over a few milliseconds instead.
A tiny loop-based song extender in Python
The script below synthesises a 16-second "song" (verse, chorus, verse, chorus) from sine-wave chords, computes one chroma vector per beat, finds the earlier passage that best matches the last four beats, and continues the song with whatever followed that passage. It then splices the continuation in mid-note on purpose, with and without a 20 ms crossfade, and measures the kink at the seam.
import numpy as np
SR = 8000 # sample rate (Hz), low to keep things fast
BEAT = 0.5 # seconds per beat (120 BPM)
rng = np.random.default_rng(0)
def chord(midi_notes, beats):
"""A plain sine-wave chord with a short fade in/out on each beat."""
t = np.arange(int(SR * BEAT * beats)) / SR
hz = [440 * 2 ** ((m - 69) / 12) for m in midi_notes]
x = sum(np.sin(2 * np.pi * f * t) for f in hz) / len(hz)
env = np.minimum(1, np.minimum(t, t[::-1]) / 0.01)
return x * env
# A tiny "song": verse (C - Am) and chorus (F - G), as A B A B
VERSE = np.concatenate([chord([60, 64, 67], 4), chord([57, 60, 64], 4)])
CHORUS = np.concatenate([chord([53, 57, 60], 4), chord([55, 59, 62], 4)])
song = np.concatenate([VERSE, CHORUS, VERSE, CHORUS])
song += 0.01 * rng.standard_normal(len(song)) # a little noise
print(f"original length: {len(song) / SR:.1f} s")
# 1. Chroma features: fold FFT energy into 12 pitch classes per beat
HOP = int(SR * BEAT)
def chroma(frame):
spec = np.abs(np.fft.rfft(frame * np.hanning(len(frame))))
freqs = np.fft.rfftfreq(len(frame), 1 / SR)
c = np.zeros(12)
ok = freqs > 50
pcs = np.round(12 * np.log2(freqs[ok] / 440) + 69).astype(int) % 12
np.add.at(c, pcs, spec[ok] ** 2)
return c / (np.linalg.norm(c) + 1e-9)
frames = np.array([chroma(song[i:i + HOP]) for i in range(0, len(song) - HOP + 1, HOP)])
print(f"beats analysed: {len(frames)}")
# 2. Self-similarity: compare the last 4 beats with every earlier 4-beat window
W = 4
tail = frames[-W:]
scores = []
for start in range(0, len(frames) - 2 * W + 1):
win = frames[start:start + W]
scores.append((float(np.mean(np.sum(win * tail, axis=1))), start))
scores.sort(reverse=True)
for s, start in scores[:3]:
print(f" window at beat {start:2d} ({start * BEAT:4.1f} s): similarity {s:.3f}")
# 3. Jump: after the best-matching window, continue with what followed it
best_score, best_start = scores[0]
jump = (best_start + W) * HOP
def join(a, b, fade):
"""Concatenate a and b, optionally with a linear crossfade of `fade` samples."""
if fade == 0:
return np.concatenate([a, b])
ramp = np.linspace(0, 1, fade)
mid = a[-fade:] * (1 - ramp) + b[:fade] * ramp
return np.concatenate([a[:-fade], mid, b[fade:]])
# 4. Splice mid-note on purpose (370 ms before the end, 37 samples out of phase)
cut = len(song) - int(0.37 * SR)
head = song[:cut]
cont = song[jump - int(0.37 * SR) + 37:]
fade = int(0.02 * SR) # 20 ms
hard = join(head, cont, 0)
soft = join(head, cont, fade)
def click_score(x, centre, radius=200):
"""Largest second difference near `centre`: sudden kinks in the waveform."""
seg = x[centre - radius:centre + radius]
return float(np.max(np.abs(np.diff(seg, 2))))
print(f"jump target: {jump / SR:.1f} s (what followed the matching window)")
print(f"click score inside the original: {click_score(song, len(song) // 3):.3f}")
print(f"click score at seam, hard cut: {click_score(hard, cut):.3f}")
print(f"click score at seam, 20 ms fade: {click_score(soft, cut - fade // 2):.3f}")
print(f"extended length: {len(soft) / SR:.1f} s")
Running it with Python 3 and NumPy prints:
original length: 16.0 s
beats analysed: 32
window at beat 12 ( 6.0 s): similarity 1.000
window at beat 13 ( 6.5 s): similarity 0.834
window at beat 11 ( 5.5 s): similarity 0.750
jump target: 8.0 s (what followed the matching window)
click score inside the original: 0.072
click score at seam, hard cut: 0.316
click score at seam, 20 ms fade: 0.101
extended length: 24.0 s
Reading the output
- The search finds the repeat. The last four beats (the G chord at the end of the second chorus) match the window at beat 12 perfectly, because that is the same G chord at the end of the first chorus. A similarity of 1.000 is only possible because this toy repeats itself exactly; real recordings vary from take to take and score lower.
- The jump target is musically sensible. What followed the first chorus was the second verse at 8.0 s, so the extended song goes chorus, then verse again, the way a real arrangement might.
- Crossfades matter. The click score is the largest second difference of the waveform near a point, a crude measure of sudden kinks. Inside the original it is 0.072. A hard, out-of-phase cut pushes it to 0.316 at the seam, while a 20 ms crossfade brings it down to 0.101, much closer to the normal signal.
From toy to real tool
A production extender would need much more:
- Beat tracking instead of assuming a fixed 120 BPM, so jumps land on real downbeats
- Richer features such as timbre (MFCCs) alongside chroma, so a quiet verse is not confused with a loud chorus in the same key
- Multiple candidates and a rule against jumping to the same place every time, so the extension does not sound obviously looped
- Stems. Working on separated vocals and instrumentals lets you loop an instrumental section without cutting a sung word in half. A stem splitter such as the Voicestars AI stems splitter, Moises or the open-source Demucs model can produce them
In practice, many workflows combine both approaches: loop or repeat existing sections for structure, and use a generative extend feature only where you really need new material, such as a fresh ending.
Copy the script, change the chord progression or the window size W, and see how the similarity scores and the chosen jump target change.
Disclosure: this article was written in partnership with Voicestars.
Top comments (0)