DEV Community

Tania Alwan
Tania Alwan

Posted on

Music Generator AI Under the Hood: A Tiny Melody Generator in Python, From Training Notes to a WAV File

By Tania Alwan

Every music generator AI I've tried feels a bit like magic from the outside: type a prompt, get a song. As a musician, I wanted to see the basic idea with the magic removed. What does it mean for a model to "learn" music and then "generate" it?

In this post I explain the main pieces in plain terms, then build a deliberately tiny melody generator in Python that learns from three short tunes and writes the result to a WAV file you can play.

How music generator AI works, in broad strokes

Modern music generators are large neural networks trained on a lot of audio, symbolic music (like MIDI) or both. The details differ between tools, but most follow the same loop:

  • Represent music as tokens. Audio is compressed into sequences of discrete codes, or notes are written as events such as pitch, duration and timing
  • Learn what usually comes next. During training, the model learns the probability of the next token given the tokens before it, or learns to turn noise into music step by step, as in diffusion models
  • Condition on a prompt. Text descriptions, genres, lyrics or a reference melody steer what the model generates
  • Sample, then decode. The model produces new tokens one after another, and a decoder turns them back into audio

The key idea is the second point: generation is sampling from patterns learned from data. You can see that idea at a tiny scale with a much older technique.

The toy version: a second-order Markov chain over notes

A Markov chain picks the next item using only the last few items. Here, the "model" is simply a table: for every pair of notes in the training melodies, which notes came next? Generating means starting from a pair and repeatedly picking a next note from that table.

The script below:

  • trains on three short melodies I wrote in C major for this post
  • builds a table from every pair of notes to the notes that followed it
  • samples 16-note melodies and keeps the first one that ends on a C, a simple musical constraint
  • converts note names to frequencies with the equal-temperament formula (A4 = 440 Hz)
  • renders the melody as sine tones into a 16-bit mono WAV file

The whole script is 68 lines and uses only the Python standard library.

import math
import random
import struct
import wave
from collections import defaultdict

# Three short melodies I wrote for this post, as note names in C major.
TRAINING = [
    "C4 D4 E4 G4 E4 D4 C4 D4 E4 E4 D4 C4",
    "E4 G4 A4 G4 E4 D4 C4 D4 E4 G4 E4 C4",
    "G4 A4 G4 E4 D4 E4 G4 A4 C5 A4 G4 E4 D4 C4",
]

NOTE_INDEX = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}

def note_to_freq(note):
    """'A4' -> 440.0 Hz, using equal temperament."""
    name, octave = note[:-1], int(note[-1])
    midi = 12 * (octave + 1) + NOTE_INDEX[name]
    return 440.0 * 2 ** ((midi - 69) / 12)

def build_chain(melodies, order=2):
    """Map each pair of notes to the notes that followed it."""
    chain = defaultdict(list)
    for melody in melodies:
        notes = melody.split()
        for i in range(len(notes) - order):
            chain[tuple(notes[i:i + order])].append(notes[i + order])
    return chain

def generate(chain, rng, length=16, tries=1000):
    """Sample melodies until one has the right length and ends on C."""
    starts = [key for key in chain if key[0] in ("C4", "E4", "G4")]
    for _ in range(tries):
        notes = list(rng.choice(starts))
        while len(notes) < length:
            options = chain.get(tuple(notes[-2:]))
            if not options:
                break
            notes.append(rng.choice(options))
        if len(notes) == length and notes[-1].startswith("C"):
            return notes
    return None

def render(notes, path, beat=0.3, rate=22050):
    """Write the melody as a mono 16-bit WAV of sine tones with short fades."""
    frames = bytearray()
    for note in notes:
        freq, n = note_to_freq(note), int(beat * rate)
        for i in range(n):
            fade = min(1.0, i / 300, (n - i) / 300)
            sample = 0.4 * fade * math.sin(2 * math.pi * freq * i / rate)
            frames += struct.pack("<h", int(sample * 32767))
    with wave.open(path, "wb") as wav:
        wav.setnchannels(1)
        wav.setsampwidth(2)
        wav.setframerate(rate)
        wav.writeframes(bytes(frames))

if __name__ == "__main__":
    print("A4 =", round(note_to_freq("A4"), 2), "Hz | C4 =", round(note_to_freq("C4"), 2), "Hz")
    chain = build_chain(TRAINING)
    print("after (E4, D4) the training data has:", chain[("E4", "D4")])
    rng = random.Random(42)
    melody = generate(chain, rng)
    print("generated:", " ".join(melody))
    render(melody, "melody.wav")
    print("wrote melody.wav,", len(melody), "notes")
Enter fullscreen mode Exit fullscreen mode

Running it with Python 3 prints:

A4 = 440.0 Hz | C4 = 261.63 Hz
after (E4, D4) the training data has: ['C4', 'C4', 'C4', 'E4', 'C4']
generated: C4 D4 E4 E4 D4 C4 D4 E4 G4 A4 C5 A4 G4 E4 D4 C4
wrote melody.wav, 16 notes
Enter fullscreen mode Exit fullscreen mode

It also writes melody.wav, about five seconds of simple sine tones you can open in any audio player or DAW.

Reading the output

The frequency check is a good sanity test: A4 comes out at exactly 440 Hz and middle C at about 261.63 Hz, which matches the standard equal-temperament values.

The line about (E4, D4) shows what "training" means here. In the three melodies, that pair is followed by C4 four times and E4 once. So when the generator reaches E4 D4, it picks C4 about 80% of the time. That's a learned probability, in the smallest form possible.

The generated melody is the interesting part. Its first eight notes are stitched together from fragments of my first tune, then the pairs D4 E4 and E4 G4 lead it into a phrase only my third tune has, climbing to C5 before resolving to C4. The full sequence doesn't appear in any training melody, but every single step was copied from one.

Where this toy model falls short

A few honest caveats:

  • No rhythm. Every note has the same length. Real generators model duration, timing and groove, which matter as much as pitch.
  • Tiny memory. Two notes of context can't keep a verse and chorus structure. Neural models use much longer context for that.
  • Small data means copying. With three melodies, the chain can only remix fragments it has seen. That's an extreme version of a real concern: models trained on music can reproduce parts of their training data, which is one reason training data and rights are such active debates.
  • Sine waves aren't instruments. Real systems generate full audio with timbre, harmony and vocals, which is far harder than a melody line.

Trying a full music generator AI next to your code

Once you've seen the principle, it's worth comparing with a production system. Tools such as Suno and Udio generate complete songs from a text prompt, and the Voicestars AI song generator lets you set options like genre, mood and tempo. Listen for what the toy can't do: rhythm, arrangement and a structure that develops over time.

Then come back and extend the script: add durations to each token, train on your own melodies, or raise the order of the chain to 3 and see how much more it copies.

Disclosure: this article was written in partnership with Voicestars.

Top comments (0)