The Patchbay_

Generate Music with MusicGen (Python)

A step-by-step guide to installing Meta's MusicGen and generating instrumental music from a text prompt — plus melody-conditioned generation — in a few lines of Python.

What you'll need

Install

pip install audiocraft

MusicGen ships inside Meta's AudioCraft library. The install pulls in PyTorch; on some setups you'll want to install a CUDA build of PyTorch first.

Your first generation

from audiocraft.models import MusicGen
from audiocraft.data.audio import audio_write

model = MusicGen.get_pretrained('facebook/musicgen-small')
model.set_generation_params(duration=8)  # seconds

wav = model.generate(['upbeat 80s synthwave with a driving bassline'])
for i, one in enumerate(wav):
    audio_write(f'clip_{i}', one.cpu(), model.sample_rate, strategy='loudness')

That downloads the musicgen-small model, generates eight seconds from the text prompt, and writes a loudness-normalised clip_0.wav. Swap in musicgen-medium or musicgen-large for higher quality at the cost of speed and memory.

Condition on your own melody

The melody model follows a tune you provide while taking its style from the text prompt:

import torchaudio
from audiocraft.models import MusicGen
from audiocraft.data.audio import audio_write

model = MusicGen.get_pretrained('facebook/musicgen-melody')
model.set_generation_params(duration=12)

melody, sr = torchaudio.load('hummed_idea.wav')
wav = model.generate_with_chroma(
    ['lofi hip hop, warm rhodes, vinyl crackle'],
    melody[None], sr)
audio_write('with_melody', wav[0].cpu(), model.sample_rate, strategy='loudness')

Prompting tips

Licence check. AudioCraft's code is MIT, but the MusicGen weights are released under CC-BY-NC — non-commercial. Confirm the current terms before you sell or monetise generated audio.

Next: run Stable Audio Open locally, or see MusicGen alternatives.

← AI music generation hub