Skip to main content

MUSIC — PROGRAM YOUR OWN MUSIC

Music DSL is a text-based music programming language. Write songs in a plain text file, play them instantly through your speakers, or export to WAV/MIDI. No instruments, DAWs, or audio editing required.

tempo: 120   name: My Song   key: C

-- melody: organ 0.4 0.2 reverb:0.3 --
C4 q  E4 q  G4 q  C5 q

-- bass: sawtooth 0.3 -0.3 filter:lp 400 --
C3 h  F3 h  G3 h  C3 h

Installation

Prerequisites

  • Python 3.10+
  • NumPy (pip install numpy)
  • sounddevice (optional, for playback): pip install sounddevice

Install

cd music-dsl/
pip install .
pip install -e .        # editable mode (development)

or

pip install music-dsl

System-wide install (Linux)

sudo ./install.sh       # creates venv at /opt/music, installs dependencies

Verify

music --help
music music/samples/night_drive.music   # play a sample
python3 -m music --help                 # alternative invocation

Usage

music song.music                 play a song
music song.music --loop 0        loop forever (Ctrl-C to stop)
music song.music --from 30 --to 60   play only seconds 30–60
music --check song.music         lint without playing (errors + warnings)
music --new song.music --style synthwave   start from a template
music --export song.music out.wav     export to WAV
music --export song.music out.mp3     export to MP3 (needs ffmpeg or soundfile)
music --midi song.music out.mid  export to MIDI
music --import-midi file.mid     import & play MIDI
music --import-midi file.mid out.music  import MIDI → .music
music --list-instruments         show all 45 instruments
music --live                     interactive jamming session (REPL)
music song.music --wave          play with waveform visualizer
python3 -m music song.music      alternative invocation

Starting a new song

music --new my.song --style synthwave   # synthwave / rock / jazz / ambient / hiphop / blank
music --new my.song --style rock --title "Thunder Road" --tempo 140

Each template is a complete, ready-to-play song — sections, chord progression, drums, bass and melody all wired up. Edit, render, done.

Checking a song

music --check my.song

Reports parse errors (unclosed blocks, unknown instruments with "did you mean" suggestions, unknown sections in arrange:) and warnings (unbalanced bars, tracks shorter than the arrangement, missing sections).

Interactive mode

music --live              # start a blank jam
music --live song.music   # load a song and jam on top

REPL commands:

:track name instrument [vol] [pan]   start a track
:tempo 132            :key Am        :dyn mf        :fx reverb:0.4
:play                 render + hear the current sketch
:undo                 step back       :clear   start over
:save mysong.music    :quit

Anything that isn't a : command is a normal DSL line (notes, @arp, @drums, patterns, ...). Press Enter twice to render and listen.


Python API

Use Music DSL programmatically from Python:

from music import load, Song, Track, Note, midi_to_song, song_to_text, lint

# Parse a .music file
song = load("path/to/song.music")

# Play through speakers
song.play()

# Export — .wav, .mp3 or .ogg
song.save("out.wav")              # WAV file
song.save("out.mp3")              # MP3 (needs ffmpeg or soundfile)
song.to_midi("out.mid")           # Standard MIDI File

# Inspect & lint
song.show()                       # print track summary to stdout
print(song.total_beats())         # total duration in beats
text = song.to_text()             # Song → .music DSL text (via MIDI roundtrip)
errors, warnings = lint("path/to/song.music")   # two lists: errors, warnings

Building a song in code

from music import Song, Track, Note

song = Song()
song.tempo = 120
song.name = "Code Song"

track = Track("melody", "piano", vol=0.5, pan=0.0)
track.line("C4 q E4 q G4 q C5 q", key_acc={})
song.add(track)

song.save("code_song.wav")

Importing MIDI

from music import midi_to_song

song = midi_to_song("file.mid")   # returns a Song object
song.play()

Language Reference

File-level directives

Place these at the top of a .music file:

tempo: 120          # BPM (default 120)
name: My Song       # title
key: C              # major: C G D A E B F# C# F Bb Eb Ab Db Gb Cb
key: Am             # minor: Am Em Bm F#m C#m Dm Gm Cm Fm Bbm
key: none           # no key signature
time: 4/4           # time signature (default 4/4)

Song structure & generation:

progression: Cm Ab Eb Bb        # chord loop, one bar per chord (see @gen)
arrange: intro verse chorus chorus outro   # section order (see Sections)
degrees:on                      # scale-degree note mode (see Degrees)

Master bus:

master: vol 0.9 comp 0.5 4 reverb 0.15 delay 0.1

master: controls the final mix — vol (0–1), comp THRESH RATIO (threshold 0–1 linear, ratio like 4 for 4:1), reverb and delay (wet mix applied to the whole song).

Comments

# This is a full-line comment
C4 q  # This is an inline comment

Tracks

A track has a name, instrument, volume, pan, and optional effects:

-- name: instrument vol pan options --
-- melody: organ 0.4 0.2 reverb:0.3 --
-- bass: sawtooth 0.3 -0.3 swing:0.6 --
-- rhythm: noise 0.15 0.0 mute --    # silenced track

Track header options:

Option Values Description
vol 0.0–1.0 Volume
pan -1.0–1.0 Panning (left→right)
reverb 0.0–1.0 Reverb mix
delay 0.0–1.0 Delay mix
swing 0.0–1.0 Swing/shuffle amount
sidechain name[:amt] Duck this track under another (0.0–0.9, default 0.5)
degrees on/off Scale-degree note mode for this track
mute — Silences the track

Sidechain ducking — classic pumping, e.g. bass under a kick:

-- kick: kick 0.7 --
C2 q C2 q C2 q C2 q

-- bass: saw 0.5 sidechain:kick:0.6 --
C2 w

Also works as a line inside the track body: sidechain:kick 0.6.

Shorthand — create a track with just an instrument name:

inst: piano 0.5 0.0     # name=instrument, vol=0.5, pan=0.0

Effect lines (placed inside the track body, one per line):

reverb:0.3
delay:0.2
swing:0.5
adsr:0.01 0.05 0.8 0.1   # attack decay sustain release
filter:lp 800 0.7         # lowpass/highpass/bandpass + freq + Q
dist:0.3                  # waveshaping distortion
lfo:filter 2 200 500      # LFO → filter (rate depth base)
humanize timing:0.02 vel:0.1  # random timing & velocity variation

Effects are additive across lines (multiple reverb: lines sum, multiple filter: lines replace).

Notes

C4 q    D#4 e    Bb3 h    F4 w

Pitch: A B C D E F G with optional #/b accidental, followed by an octave number (4 = middle C, range 0–9).

Durations (sticky — applies to subsequent notes until changed):

Code Beats Code Beats
w 4 (whole) e 0.5 (eighth)
h 2 (half) s 0.25 (sixteenth)
q 1 (quarter) t 0.125
x 0.0625 (sixty-fourth)

Duration modifiers:

C4 q.           # dotted (1.5x)
C4 q..          # double-dotted (1.75x)
C4 qt           # triplet (2/3x)
C4 _1.5         # raw duration in beats
C4 _0.253       # fractional beats (e.g. from MIDI import)

Rests:

R q    R e    R _2    rest q    _ q

Bar lines

|             # bar line (warns if bar overflows)
||            # double bar line

Sections & Repeats

[verse]
C4 q  E4 q  G4 q
@jump verse       # repeat indefinitely

@done              # stop playback here (rest of track ignored)

[label] marks a position, @jump label jumps back to it. @done stops playback.

Repeat a block N times:

[ C4 q E4 q G4 q ] x4
[ C4 e R e ] x32

Multi-line repeats:

[ C4 q E4 q
  G4 q C5 q ] x3

Volta endings (1st and 2nd endings):

[1 C4 q D4 q E4 q]      # play on first pass
[2 C4 q D4 q F4 q]      # play on second pass

Song sections & arrangement

%name starts a named section (different from [label], which is for @jump flow control). Define sections per track, then set the song order with arrange::

progression: Cm Ab Eb Bb
arrange: intro verse chorus chorus outro

-- bass: bass 0.5 --
%intro
R w
%verse
@gen bass 8ths
%chorus
@gen bass 8ths oct
%outro
C2 w

-- lead: organ 0.4 --
%chorus
C5 e Eb5 e G5 e C6 e  G5 q Eb5 e C5 e

Rules:

  • Each section's length is the longest track's content in it — shorter tracks are automatically rest-padded, so everything stays in sync.
  • xN repeats a section: arrange: intro verse chorus x2 outro.
  • Every section named in arrange: must be defined by at least one track (otherwise --check reports an error).
  • Tracks with no %sections (or with @gen drums) play linearly from the start — they ignore the arrangement.
  • After arranging, the song plays only in arrange: order; sections not listed are dropped.

Chord progression & generators

progression: Cm Ab Eb Bb        # one bar per chord; xN repeats the loop

With a progression defined, @gen writes whole parts for you — one bar per chord:

-- bass: bass 0.5 --
@gen bass 8ths          # eighth-note bass, root-fifth
@gen bass quarters root # quarter notes, root only
@gen bass 8ths root8 oct2   # +2 octaves (oct / oct2 / oct-1)

-- pad: strings 0.2 --
@gen pad                # whole-note chord bed (oct for upper voicing)

-- arp: tri 0.3 --
@gen arp 8ths           # up; also: down / ud / rand, plus 16ths/quarters

@gen drums four         # creates gen_kick / gen_snare / gen_hat tracks

Bass styles: root (root only), root5 (root-octave alternating — default), root8 (octave-jumping). Bass/pad/arp durations: 8ths (default), quarters, 16ths, half, whole. Drum styles: four, rock, half, break, shuffle.

@gen drums is deferred until the whole song is arranged, so the groove covers the full arrange: length.

Scale degrees (Nashville-style)

degrees:on
1 q 4 q 5 q 6m h        # I IV V vi in the song's key

With degrees:on (or degrees: on a track header), pitch tokens become scale degrees relative to key::

  • 1–7 — scale degree (#/b accidentals allowed: b7, #4)
  • ' / , — octave up / down (4' = degree 4, one octave up)
  • chord quality suffix — 6m, 1maj7, 5m7 … plays the chord on that degree
  • degrees:off returns to normal note names

key: C + 1 q 4 q 5 q → C4 F4 G4; key: Am + 1 q → A4.

Arpeggiator

@arp up C q             # C4 E4 G4 — one per beat
@arp down Cmaj7 e       # B4 G4 E4 C4 in eighths
@arp ud (C4 E4 G4) s    # up-down over a note list
@arp rand C q           # randomized order

Directions: up (default), down, ud (up then down), downup, rand. Takes a chord symbol (Cmaj7), a parenthesized note list, or the previous chord; optional duration at the end.

Drum step shorthand

@drums 8 { x . x . x . X . }   # 8 steps, X = accent, g = ghost, . = rest
@drums x-x-x-x | x-x-x-x       # bar-separated shorthand

Each step gets current_duration / nsteps — set the sticky duration first (q = quarter-note steps, e = eighths, ...). Notes land on the current track's instrument, so use a drum voice:

-- sn: snare 0.5 --
e @drums 8 { x . g . x . x . }

Chords

Simultaneous notes (parenthesized group):

(C4 E4 G4) q        # C major chord
(C4 E4 G4 C5) h     # add octave

Chord symbols (shorthand):

C  q    Cm  q    C7  q    Cmaj7  q

A letter alone (C) is a major triad. Chord type is appended directly (no space):

Symbol Type Symbol Type
(none) Major m / min Minor
maj7 / M7 Major 7th m7 Minor 7th
7 Dominant 7th dim Diminished
dim7 Diminished 7th aug Augmented
sus4 / sus Suspended 4th sus2 Suspended 2nd
6 Major 6th m6 Minor 6th
9 Dominant 9th add9 Add 9
m7b5 Half-diminished m9 Minor 9th

Chord voicing starts at octave 4 by default. To specify octave, use the parenthesized form.

Note: Pitch names ending in a digit (C7, F#7, Bb9) are parsed as single notes, not chord symbols. Use G7 for the note G at octave 7; use (G B D F) q for a G7 chord.

Ties & Articulations

C4 w ~ C4 q          # tie (sustain across barline)
C4~ q                # legato (no gap between notes)
C4. q                # staccato (50% duration)
Modifier Effect
. after pitch Staccato (shorten by 50%)
~ after pitch Legato (no gap before next)
~ between notes Tie (sustain through)

Dynamics

ppp  pp  p  mp  mf  f  ff  fff  sffz

Set global dynamics for subsequent notes. A bare dynamics word on its own line sets the level for all following lines in that track (useful for section-level dynamics). fp starts loud then soft.

ppp = 0.15   pp = 0.25   p = 0.35   mp = 0.50
mf = 0.70    f = 0.85    ff = 1.00  fff = 1.20
sffz = 1.30  fp = (1.00 → 0.35)

Accent markings

>C4 q    ^D4 q    +E4 q

Apply directly before a pitch name. Boosts note velocity:

Mark Name Velocity multiplier
> Accent ×1.3
^ Marcato ×1.5
+ Sforzando ×1.8

Note velocity override

C4 q @0.63     # set C4 velocity to 0.63 (overrides default 0.8)

@N after a note sets its velocity directly (0.0–1.0).

Expression effects

vibrato:5            # pitch LFO rate (Hz)
tremolo:3            # amplitude LFO rate (Hz)
portamento:0.15      # pitch slide duration (seconds)

Set per-track. Values persist until changed.

Note probability

C4 q ?0.5 D4 q E4 q   # D4 has 50% chance of silence

?N sets the probability (0.0–1.0) for all subsequent notes in that track. Notes roll against the probability each time they play; skipped notes become rests of equal duration. Reset with ?1.0.

Crescendo & Diminuendo

< C4 q D4 q E4 q >   # notes get progressively louder

< starts a velocity ramp (starting velocity → ×1.4), > ends it. All non-rest notes between receive linearly increasing velocity.

Inline tempo & time signature changes

C4 q D4 q tempo:160 E4 q F4 q
C4 q D4 q time:3/4 C4 q D4 q E4 q

tempo:BPM and time:N/D can appear inside a note sequence to change tempo or time signature mid-song. Also work as file-level directives.

Tuplets

3:2 {C4 D4 E4}           # triplet (3 notes in the space of 2)
5:4 {C4 D4 E4 F4 G4}    # quintuplet (5 in the space of 4)
6:4 {C4 D4 E4 F4 G4 A4} # sextuplet

The first number is how many notes, the second is the base duration (in units of the current sticky duration). Grace notes:

{C4 D4} E4 q    # acciaccatura (grace notes, very short)

Key signature

Key signatures apply accidentals automatically:

key: D             # F# and C# are raised
key: Bb            # Bb and Eb
key: Fm            # Bb, Eb, Ab, Db

Use key: none or key: C for no accidentals. Accidentals on individual notes (C#4, Bb3) override the key signature.

Transpose

@ transpose 2     # all subsequent notes up 2 semitones
@ transpose -12   # down one octave

Voice assignment

voice:2           # assign subsequent notes to MIDI voice 2

Used for MIDI roundtrip fidelity when a channel contains multiple independent lines.

Patterns

Reusable note sequences:

Single-line definition:

@pattern arp = C4 e E4 e G4 e C5 e
@ost = C2 e G2 e C3 e G2 e          # shorthand: @name = ... works too

Multi-line definition:

@pattern bassline
C2 e G2 e C3 e G2 e
Ab1 e Eb2 e Ab2 e Eb2 e
@end

Invocation:

@arp
@bassline

Step sequencer

@steps 8 { C4 . D4 . E4 . F4 . }

Each step gets current_duration / nsteps duration. Dots (.) or R produce rests within the step pattern.

Random / stochastic commands

@coin C4 D4 E4          # 50% chance to play one random note
@coin 0.3 C4 D4         # 30% chance
@rand C4 D4 E4 F4       # always play one random note from the list
@choose C4 D4 E4        # play ALL notes, each shortened proportionally
@shuffle C4 D4 E4 F4    # play all notes in random order

Include

@include other_song.music    # import tracks from another .music file

Tracks from the included file are added to the current song using the current track's instrument.

Track mute

-- rhythm: guitar 0.3 mute --

Add mute anywhere in the track header to silence it during playback. Useful for arranging or A/B testing parts without deleting them.


Instruments

45 instruments organized by category. Each has a natural default ADSR envelope; override with adsr: in the track body.

Basic Waveforms

Name Aliases Description
sine — Pure sine wave
square — Square wave (polyBLEP anti-aliased)
saw sawtooth Saw wave (polyBLEP anti-aliased)
tri triangle Mellow triangle wave
noise — White noise

Keyboard

Name Aliases Description
piano — Rich piano (inharmonic partials)
organ — Hammond-style drawbar organ with Leslie tremolo
harpsichord — Bright plucked keyboard (Karplus-Strong)
clavinet — Funky electric keyboard
celesta — Soft bell-like keyboard

Plucked Strings

Name Aliases Description
guitar — Steel-string guitar (Karplus-Strong)
nylon — Nylon-string guitar (warmer KS)
harp — Warm resonant harp (KS, long decay)
banjo — Bright twangy banjo (KS, high brightness)
sitar — Buzzing Indian sitar (jawari + sympathetic resonance)
kalimba — Thumb piano (soft metallic pluck)

Bowed / Sustained

Name Aliases Description
strings pad 3-voice detuned string ensemble
bass — Sub-oscillator bass with soft saturation
choir — Vocal ensemble with formant shaping

Wind

Name Aliases Description
flute — Pure tone with breath noise
brass — Bright brass with attack blip
reed sax Nasal woodwind (even+odd harmonics + breath)
accordion — Free-reed with wet tuning tremolo

Bells & Mallets

Name Aliases Description
bell — Inharmonic metallic bell
pluck — Percussive noise burst
marimba — Wooden bar (short inharmonic)
xylophone — Bright wooden bar (shorter than marimba)
vibraphone — Metal bar with motor tremolo
steel_drums — Metallic tropical steel pan

Percussion

Name Aliases Description
kick — Bass drum (sine sweep + click)
snare — Snare drum (tone + filtered noise)
hihat — Closed hi-hat (short highpass noise)
hihat_open — Open hi-hat (longer decay)
cymbal — Crash cymbal (bright metallic noise)
ride — Ride cymbal (noise + tonal ping)
tom — Tom drum (pitched sine sweep)
clap — Hand clap (layered noise bursts)
rimshot — Rimshot (short click + tone)
cowbell — Cowbell (two-tone metallic)
tambourine — Tambourine (noise + metallic jingle)
maracas — Maracas (short highpass shake)

Sample Songs

Located in music/samples/:

music music/samples/night_drive.music
File Tempo Duration Style
night_drive.music 94 BPM 165s Synthwave / retrowave
empire_fire.music 174 BPM 66s War march / orchestral
chaos.music 178 BPM — Storm of iron / battle
skybound.music — — Cinematic
machine.music — — Industrial
iron_clash.music — — Percussive
last_stand.music 162 BPM 95s Epic finale
tragedy.music — — Dark / melancholic

MIDI Import/Export

Import MIDI → play or convert

music --import-midi song.mid              # import & play
music --import-midi song.mid out.music    # import → .music DSL file

The importer maps General MIDI programs to the closest built-in instrument:

Piano/Keys→piano,harpsichord,clavinet,celesta Guitar→guitar,nylon Bass→bass Strings→strings Pad→pad Organ→organ Accordion→accordion Brass→brass Woodwinds→reed,sax Flute→flute Choir→choir Mallets→marimba,xylophone,vibraphone,celesta Plucked→harp,banjo,sitar,kalimba,steel_drums Leads→saw,square,sine

Percussion channel (GM ch10) maps to dedicated drum instruments: kick, snare, hihat, hihat_open, cymbal, ride, tom, clap, rimshot, cowbell, tambourine, maracas.

Polyphonic voices within a MIDI channel are automatically split into separate tracks. Duration codes use the raw _N.NNN format to preserve exact MIDI timing.

Export to MIDI / WAV / MP3

music --midi song.music out.mid      # export to Standard MIDI File
music --export song.music out.wav    # export to WAV audio file
music --export song.music out.mp3    # MP3 — needs ffmpeg or the soundfile lib
music --export song.music out.ogg    # OGG — same backends as MP3

Without either backend installed, the export command fails with a clear message instead of writing a broken file.


Audio Engine

Playback backends (auto-detected)

  1. sounddevice — preferred, low-latency
  2. PyAudio — fallback
  3. aplay / paplay / pw-play — system audio tools

Per-track effects chain

  1. Waveform synthesis (oscillator)
  2. ADSR envelope
  3. Staccato / legato articulation
  4. Vibrato, tremolo, portamento
  5. Volume & pan
  6. Filter (lowpass / highpass / bandpass)
  7. LFO-modulated filter
  8. Waveshaping distortion
  9. Reverb
  10. Delay
  11. Humanization (random timing & velocity)

Mix bus

  1. Sidechain ducking (per-track, keyed off another track's onsets)
  2. Master compressor (master: comp THRESH RATIO)
  3. Master reverb & delay (master: reverb X delay X)
  4. Master volume + peak normalization

Editors

Syntax highlighting for .music files ships in editors/:

  • VS Code — full extension in editors/vscode/ (open the folder and press F5, or package with vsce and install the .vsix)
  • Vim / Neovim — editors/vim/syntax/music.vim + editors/vim/ftdetect/music.vim (copy into ~/.vim/ or ~/.config/nvim/, or use vim-plug pointing at editors/vim)

See editors/README.md for install details.


Testing

The test suite covers the parser, generators, arrangement, rendering, exports, CLI and the live REPL:

python3 -m pytest tests/ -q     # pytest
python3 tests/test_dsl.py       # standalone (no pytest needed)

License

MIT — use it, tweak it, make music with it.

Metadata

Release files for music-dsl 3.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for music-dsl 3.0.0
File Size Uploaded Provenance Actions
music_dsl-3.0.0.tar.gz 89.8 kB Without provenance Details for music_dsl-3.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for music-dsl 3.0.0
File Interpreter ABI Platform Actions
music_dsl-3.0.0-py3-none-any.whl Python 3 none any Details for music_dsl-3.0.0-py3-none-any.whl

Total release size: 165.9 kB

Release files / music_dsl-3.0.0.tar.gz

Download URL music_dsl-3.0.0.tar.gz
Size 89.8 kB
Tags Source
SHA-256 checksum
How to use checksums
b791a30f2608fdd9d8cb6cdb8a50fb60e80d86c39a12de06f6c2fdba96d91f32
BLAKE2b-256 checksum
How to use checksums
50a2b5e9607f68049cccd0f4c62bdc6b90857d2df6d2a1f2c0e83c1af6a85ee6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.12

Release files / music_dsl-3.0.0-py3-none-any.whl

Download URL music_dsl-3.0.0-py3-none-any.whl
Size 76.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
541a066aaadaaa265e6719a373fa70ccc63ad9f84bb6da3a6d3b8f1dbaec4396
BLAKE2b-256 checksum
How to use checksums
ba59e56d4807d36d91dc2bc4f945404579df4c77d7195cc41896248e04f078b6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.12

Security for music-dsl 3.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

3.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page