Tunes
A Rust library for music composition, synthesis, and audio generation. Build complex musical pieces with an intuitive, expressive API.
Install / Use
/learn @sqrew/TunesREADME
tunes
A standalone Rust library for music composition, synthesis, and audio generation with real-time, concurrent playback and control. Build complex musical pieces with an intuitive, expressive API — no runtime dependencies required. Perfect for algorithmic music, game audio, generative art, and interactive installations.
Performance: CPU synthesis measured at 100x realtime (uncached) and 20.0x realtime (cached complex compositions) on decade old hardware. SIMD sample playback: 1000+ with true concurrent playback (all samples playing simultaneously)** - can handle 500-1500+ concurrent samples in real-world scenarios. Optional GPU acceleration available via
gpufeature - provides minimal benefit on integrated GPUs (~1.0x on i5 6500) but scales with discrete GPU hardware.
Table of Contents
- Features
- Who this is and isn't for
- PROS / CONS
- Installation
- Quick Start
- Comparison with Other Libraries
- Documentation
- Testing
- Examples
- Documentation Book
- Performance & Benchmarks
- License
- Contributing
Features
- Music Theory: Scales, chords, patterns, progressions, and transposition
- Composition DSL: Fluent API for building musical sequences
- Sections & Arrangements: Create reusable sections (verse, chorus, bridge) and arrange them
- Synthesis: FM synthesis, Granular synthesis, Karplus Strong, additive synthesis, filter envelopes, wavetable oscillators
- Instruments: 150+ Pre-configured synthesizers, bass, pads, leads, guitars, percussion, brass, strings, woodwinds and more
- Rhythm & Drums: 100+ pre-configured drum sounds, drum grids, euclidean rhythms, 808-style synthesis, and pattern sequencing
- Effects, Automation and Filters: Delay, convolution reverb, distortion, parametric EQ, chorus, modulation, tremolo, autopan, gate, limiter, compressor (with multiband support), bitcrusher, eq, phaser, flanger, saturation, sidechaining/ducking, various filters, many spectral effects
- Musical Patterns: Arpeggios, ornaments, tuplets, and many classical techniques and patterns built-in
- Algorithmic Sequences: 50+ algorithms, including Primes, Fib, 2^x, Markov, L-map, Collatz, Euclidean, Golden ratio, random/bounded walks, Thue-Morse, Recamán's, Van der Corput, L-System, Cantor, Shepherd, Cellular Automaton, and many more
- Tempo & Timing: Tempo changes, time signatures (3/4, 5/4, 7/8, etc.), key signatures with modal support
- Key Signatures & Modes: Major, minor, and all 7 Greek modes (Dorian, Phrygian, Lydian, etc.)
- Real-time Playback: Cross-platform audio output with concurrent mixing, live volume/pan control
- Live Audio Recording: Record from microphone or line-in to WAV files, then process with full effects pipeline
- Sample Playback: Load and play audio files (MP3, OGG, FLAC, WAV, AAC) with pitch shifting, time dilation and slicing, powered by SIMD with auto caching for efficient sample playback
- GPU Acceleration (optional
gpufeature): GPU compute shader acceleration via wgpu for synthesis and export. Transparent API integration - enable withAudioEngine::new_with_gpu(). Performance scales with GPU hardware; integrated GPUs show minimal improvement while discrete GPUs can provide significant acceleration - WebAssembly Support (optional
webfeature): Full browser support via WebAssembly - synthesis, effects, sample playback, and real-time audio in web applications. Powered by Web Audio API through cpal's wasm-bindgen integration - Streaming Audio: Memory-efficient streaming for long background music and ambience without loading entire files into RAM (native-only)
- Spatial Audio: 3D sound positioning with distance attenuation, azimuth panning, doppler effect, and listener orientation, sound cones, and occlusion for immersive game audio
- Audio Export: WAV (uncompressed), FLAC (lossless ~50-60% compression), STEM export
- MIDI Import/Export: Import Standard MIDI Files and export compositions to MIDI with proper metadata
- Live Coding: Hot-reload system - edit code and hear changes instantly
- The library includes 1547 comprehensive tests and 659 doc tests ensuring reliability and correctness.
Who this is and isn't for:
For:
learners
tinkerers
algorithmic/generative/procedural music
experimental musicians
game jammers and indie devs,
rust coders looking to play with Digital Signal Processing without having to re-implement everything from scratch
Not for:
professional producers
DAW dwellers
DSP engineers
live-repl-first musicians
PROS
rust making music is cool
music theory integration
batteries included approach
composition and code first environment (rust's ide integration and your choice of ide is everything here)
high CPU performance and automatic simd (100x realtime synthesis uncached, 20.0x cached on complex compositions)
multi-core parallelism (automatic via Rayon)
optional GPU compute shader acceleration with transparent API
CONS
no gui or graphical elements
no "instant feedback" outside of hot-reloading segments
no external control or input (no midi in, osc or network controls) or hardware control
no plugin system
rust (not as beginner friendly as something like sonic pi)
Installation
Add this to your Cargo.toml:
[dependencies]
tunes = "1.1.0"
# Optional: Enable GPU acceleration (requires discrete GPU for best results)
# tunes = { version = "1.1.0", features = ["gpu"] }
# Optional: Enable WebAssembly support for browser-based applications
# tunes = { version = "1.1.0", features = ["web"] }
Platform Requirements
Linux users need ALSA development libraries:
# Debian/Ubuntu
sudo apt install libasound2-dev
# Fedora/RHEL
sudo dnf install alsa-lib-devel
macOS and Windows work out of the box with no additional dependencies.
WebAssembly requires wasm-pack for building:
cargo install wasm-pack
wasm-pack build --target web --features web
See book/src/advanced/wasm.md for complete WebAssembly setup and usage guide.
Quick Start: Super simple!!
Real-time Playback
use tunes::prelude::*;
fn main() -> Result<(), anyhow::Error> {
let engine = AudioEngine::new()?;
let mut comp = Composition::new(Tempo::new(120.0));
let eighth = comp.tempo().eighth_note(); //getting this value to use in the next example
// This is where you can do everything.
// Notes and chords can be input as floats with frequencies in hz or using or by prelude constants
// Durations can be input as a duration of seconds as a float or using durations inferred by tempo
comp.instrument("piano", &Instrument::electric_piano())
.note(&[C4], 0.5) //plays a c4 for half a second
.note(&[280.0], eighth); //plays 280.0 hz note for half a second
//continue chaining methods after the second note if you want.
engine.play_mixer(&comp.into_mixer())?;
Ok(())
}
Sample Playback (Game Audio - Simple!)
use tunes::prelude::*;
fn main() -> Result<(), anyhow::Error> {
let engine = AudioEngine::new()?;
// That's it! Play samples with automatic caching and SIMD acceleration
engine.play_sample("explosion.wav"); // Loads once, caches, plays with SIMD
engine.play_sample("footstep.wav"); // Loads once, caches
engine.play_sample("footstep.wav"); // Instant! Uses cache, SIMD playback
play_sample!(engine, "sample.wav"); // Works the same but has compile time path resolution and runtime startup file validation
// All samples play concurrently with automatic mixing
Ok(())
}
Export to WAV or FLAC
use tunes::prelude::*;
fn main() -> Result<(), anyhow::Error> {
let engine = AudioEngine::new()?;
let mut comp = Composition::new(Tempo::new(120.0));
// Create a melody with instruments and effects
comp.instrument("lead", &Instrument::synth_lead())
.filter(Filter::low_pass(1200.0, 0.6))
.notes(&[C4, E4, G4, C5], 0.5);
// Export to WAV (sample rate inferred from engine)
let mut mixer = comp.into_mixer();
engine.export_wav(&mut mixer, "my_song.wav")?;
// Or export to FLAC (lossless compression)
engine.export_flac(&mut mixer, "my_song.flac")?;
Ok(())
}
MIDI Import/Export
use tunes::prelude::*;
fn main() -> Result<(), anyhow::Error> {
// Export: Create and export a composition to MIDI
let mut comp = Composition::new(Tempo::new(120.0));
comp.instrument("melody", &Instrument::synth_lead())
.notes(&[C4, E4, G4, C5], 0.5);
comp.track("drums")
.drum_grid(16, 0.125)
.kick(&[0, 4, 8, 12])
.snare(&[4, 12]);
let mixer = comp.into_mixer();
mixer.export_midi("song.mid")?;
// Import: Load a MIDI file and render to audio
let engine = AudioEngine::new()?;
let mut imported = Mixer::
