Below is a self-contained “weekend-hack” style prototype that shows the essential plumbing you asked for:
• reads every .mid file in a directory
• flattens the note-events into a token sequence
• trains a tiny autoregressive model (a 2-layer GRU) with tch (PyTorch’s Rust bindings)
• samples forever, converts tokens → sine waves, and plays them through your speakers with rodio
It is not production-ready (no fancy tokenization, no GPU tricks, no tempo/rhythm modeling, etc.), but it should compile and demonstrate the full pipeline. Feel free to extend / optimise / replace pieces as you like. 🎶
──────────────────────────────── Cargo.toml
[package]
name = "midi_jam"
version = "0.1.0"
edition = "2021"
[dependencies]
rimd = "0.6" # MIDI parser
rodio = "0.17"
tch = { version = "0.13", features = ["cuda"] } # drop "cuda" if you only have CPU
rand = "0.8"
anyhow = "1.0"
──────────────────────────────── src/main.rs
mod midi;
mod model;
mod synth;
use anyhow::{Context, Result};
use midi::{load_midis_from_dir, MidiCorpus};
use model::{MusicModel, TrainingConfig};
use synth::{Player, SAMPLE_RATE};
fn main() -> Result<()> {
// 1) Load & tokenize MIDI files
let midi_dir = std::env::args()
.nth(1)
.expect("First CLI arg must be path to MIDI directory");
println!("Loading MIDI files from {midi_dir}…");
let corpus: MidiCorpus = load_midis_from_dir(&midi_dir)?;
// 2) Train language model
let cfg = TrainingConfig {
embed_dim: 128,
hidden_dim: 256,
layers: 2,
epochs: 3,
lr: 1e-3,
batch_size: 32,
};
println!("Training model… (this is just a demo; be patient)");
let mut net = MusicModel::new(&cfg, corpus.vocab_size());
net.train(&corpus, &cfg)?;
// 3) Prepare audio player
let mut player = Player::new(SAMPLE_RATE)?;
// 4) Generate forever
println!("🎹 Generating ∞ music stream — press Ctrl-C to quit.");
let mut state = net.init_state(1)?;
let mut token = corpus.tokenize_note(60); // start w/ middle-C
loop {
// autoregressive step
let (next_token, new_state) = net.sample_step(token, &state)?;
state = new_state;
token = next_token;
// decode → pcm & play
let note = corpus.detokenize_note(token);
if let Some(freq) = synth::midi_note_to_freq(note) {
player.play_sine(freq);
}
}
}
──────────────────────────────── src/midi.rs
use anyhow::{Context, Result};
use rimd::{Event, MidiMessage, SMF};
use std::{fs, path::Path};
/// Simple note-on vocabulary ───────────
/// 0..127 = NOTE-ON (pitch)
/// 128 = NOTE-OFF/REST (we keep it minimal)
pub fn note_token(pitch: u8) -> i64 { pitch as i64 }
pub fn rest_token() -> i64 { 128 }
pub fn vocab_size() -> i64 { 129 }
/// Holds the flattened token stream from all .mid files
pub struct MidiCorpus {
pub tokens: Vec<i64>,
}
impl MidiCorpus {
pub fn vocab_size(&self) -> i64 { vocab_size() }
pub fn tokenize_note(&self, pitch: u8) -> i64 { note_token(pitch) }
pub fn detokenize_note(&self, token: i64) -> Option<u8> {
if token < 128 { Some(token as u8) } else { None }
}
}
/// Walk a directory, parse .mid files, build corpus
pub fn load_midis_from_dir<P: AsRef<Path>>(dir: P) -> Result<MidiCorpus> {
let mut tokens = Vec::<i64>::new();
for entry in fs::read_dir(dir)? {
let path = entry?.path();
if path.extension().map_or(false, |x| x == "mid" || x == "midi") {
let bytes = fs::read(&path)?;
let smf = SMF::parse(&bytes).with_context(|| format!("Bad MIDI {:?}", path))?;
extract_tokens(&smf, &mut tokens)?;
println!("Loaded {:?} ({} tokens)", path.file_name(), tokens.len());
}
}
Ok(MidiCorpus { tokens })
}
/// Pick the first track, dump NOTE-ON events in order (ignore timing)
fn extract_tokens(smf: &SMF, out: &mut Vec<i64>) -> Result<()> {
for track in &smf.tracks {
for Event { vtime: _, content } in track {
if let MidiMessage::NoteOn { key, vel } = content {
if *vel > 0 {
out.push(note_token(*key));
} else {
out.push(rest_token());
}
}
}
// only first track
break;
}
Ok(())
}
──────────────────────────────── src/model.rs
use crate::midi::vocab_size;
use anyhow::Result;
use rand::seq::SliceRandom;
use tch::{
nn::{self, Module, OptimizerConfig, RNN},
Device, Kind, Tensor,
};
pub struct TrainingConfig {
pub embed_dim: i64,
pub hidden_dim: i64,
pub layers: i64,
pub epochs: i64,
pub lr: f64,
pub batch_size: usize,
}
pub struct MusicModel {
vs: nn::VarStore,
embed: nn::Embedding,
gru: RNN,
lin: nn::Linear,
device: Device,
}
impl MusicModel {
pub fn new(cfg: &TrainingConfig, vocab: i64) -> Self {
let device = Device::cuda_if_available();
let mut vs = nn::VarStore::new(device);
let root = &vs.root();
let embed = nn::embedding(root, vocab, cfg.embed_dim, Default::default());
let gru = nn::gru(
root,
cfg.embed_dim,
cfg.hidden_dim,
cfg.layers,
Default::default(),
);
let lin = nn::linear(root, cfg.hidden_dim, vocab, Default::default());
Self { vs, embed, gru, lin, device }
}
pub fn train(&mut self, corpus: &crate::midi::MidiCorpus, cfg: &TrainingConfig) -> Result<()> {
let mut opt = nn::Adam::default().build(&self.vs, cfg.lr)?;
let vocab = vocab_size();
let data = &corpus.tokens;
for epoch in 1..=cfg.epochs {
let mut rng = rand::thread_rng();
let mut idxs: Vec<_> = (0..data.len() - 1).collect();
idxs.shuffle(&mut rng);
for batch in idxs.chunks(cfg.batch_size) {
let xs: Vec<i64> = batch.iter().map(|&i| data[i]).collect();
let ys: Vec<i64> = batch.iter().map(|&i| data[i + 1]).collect();
let xs = Tensor::of_slice(&xs).to_device(self.device);
let ys = Tensor::of_slice(&ys).to_device(self.device);
let emb = xs.apply(&self.embed).unsqueeze(1); // seq_len=1
let (h, _) = self.gru.seq(&emb);
let logits = h.squeeze_dim(1).apply(&self.lin);
// cross-entropy
let loss = logits.cross_entropy_for_logits(&ys);
opt.backward_step(&loss);
}
println!("epoch {epoch}/{}/ loss={:?}", cfg.epochs, opt.loss());
}
Ok(())
}
pub fn init_state(&self, batch: i64) -> Result<Tensor> {
Ok(Tensor::zeros(
[self.gru.num_layers(), batch, self.gru.hidden_size()],
(Kind::Float, self.device),
))
}
/// one-token sample with temperature 1.0
pub fn sample_step(&self, token: i64, prev_state: &Tensor) -> Result<(i64, Tensor)> {
let x = Tensor::of_slice(&[token])
.to_device(self.device)
.apply(&self.embed)
.unsqueeze(0); // seq_len=1
let (out, new_state) = self.gru.forward(&x, Some(prev_state));
let logits = out.squeeze_dim(0).apply(&self.lin);
let probs = logits.softmax(-1, Kind::Float);
let next_token = probs
.multinomial(1, true)
.int64_value(&[0]);
Ok((next_token, new_state))
}
}
──────────────────────────────── src/synth.rs
use anyhow::Result;
use rodio::{source::Source, OutputStream, Sink};
use std::f32::consts::PI;
use std::time::Duration;
pub const SAMPLE_RATE: u32 = 44100;
const NOTE_DUR: f32 = 0.25; // seconds for each note
pub fn midi_note_to_freq(note: u8) -> Option<f32> {
if note > 127 { return None; }
let a4 = 69u8;
let a4_freq = 440.0f32;
let semitones = note as i32 - a4 as i32;
Some(a4_freq * (2f32).powf(semitones as f32 / 12.0))
}
/// Sine wave generator
fn sine_wave(freq: f32) -> impl Source<Item = f32> + Send {
let sample_rate = SAMPLE_RATE as f32;
rodio::source::SineWave::new(freq as u32).take_duration(Duration::from_secs_f32(NOTE_DUR))
}
/// Simple audio output wrapper
pub struct Player {
_stream: OutputStream, // kept alive
sink: Sink,
}
impl Player {
pub fn new(sample_rate: u32) -> Result<Self> {
let (_stream, stream_handle) = OutputStream::try_default()?;
assert_eq!(sample_rate, SAMPLE_RATE, "rodio stream is 44.1k only");
let sink = Sink::try_new(&stream_handle)?;
Ok(Self { _stream, sink })
}
pub fn play_sine(&mut self, freq: f32) {
self.sink.append(sine_wave(freq));
// free wheel: let rodio handle mixing; flush if queue too big
if self.sink.len() > 32 {
self.sink.clear();
}
}
}
How to run
# 1. create a new Rust project
cargo new midi_jam
cd midi_jam
# 2. overwrite Cargo.toml and src/* with the above code
# 3. drop a handful of monophonic .mid files into ./data
cargo run --release -- ./data
(Try starting with small monophonic melodies – Bach inventions, nursery rhymes, etc.)
Tweaks & ideas
• Make the tokenizer time-aware (encode delta-times or “time-shift” tokens).
• Switch out GRU → Transformer (tch also supports it) for better quality.
• Use GPU by installing CUDA & keeping the “cuda” feature flag.
• Replace sine synth with a proper wavetable / sample player for richer timbre.
• Stream to a file (wav/ogg) instead of speakers by swapping rodio sink.
Have fun crafting your endless AI jam! 🎵