Creating a Rust script that processes MIDI files, trains an autoregressive language model, and generates an endless audio stream involves several complex components. Below is a simplified implementation that demonstrates the core concepts. This example uses the midly crate for MIDI parsing, tch for a basic LSTM model, and cpal for audio streaming. Note that this is a minimal proof-of-concept and may require further refinement for practical use.
Key Components:
- MIDI Parsing: Extract note events using
midly.
- Tokenization: Convert MIDI notes to discrete tokens.
- Model Training: A simple LSTM using
tch.
- Audio Synthesis: Generate sine waves from MIDI notes.
- Real-Time Streaming: Use
cpal for audio playback.
Dependencies
Add these to your Cargo.toml:
[dependencies]
midly = "0.8"
tch = "0.6"
cpal = "0.13"
ndarray = "0.15"
serde = "1.0"
bincode = "1.3"
Full Implementation
use midly::Smf;
use std::fs;
use std::path::Path;
use std::sync::mpsc::{channel, Sender};
use std::thread;
use std::time::Duration;
use tch::{nn, Device, Tensor, Kind, Optimizer, Sequential};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
const SAMPLE_RATE: f32 = 44100.0;
const DURATION_MS: u64 = 500; // Duration per generated note
const NOTE_RANGE: u8 = 128; // MIDI notes 0-127
fn main() {
let midi_dir = "path/to/midi/files";
let tokens = parse_midi_directory(midi_dir);
let vocab_size = NOTE_RANGE as i64;
// Train model
let model = train_model(&tokens, vocab_size);
// Start audio stream
let (audio_tx, audio_rx) = channel();
start_audio_stream(audio_rx);
// Generate and send audio
generate_and_send_audio(&model, vocab_size, audio_tx);
}
// === MIDI Parsing ===
fn parse_midi_directory(dir: &str) -> Vec<u8> {
let mut tokens = Vec::new();
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.extension().and_then(|s| s.to_str()) == Some("mid") {
let data = fs::read(&path).unwrap();
let smf = Smf::parse(&data).unwrap();
for track in smf.tracks {
for event in track {
if let midly::TrackEventKind::Midi { message, .. } = event.kind {
if let midly::MidiMessage::NoteOn { key, .. } = message {
tokens.push(key.as_int() as u8);
}
}
}
}
}
}
tokens
}
// === Model Definition ===
fn make_model(vs: &nn::Path, input_size: i64, hidden_size: i64, output_size: i64) -> Sequential {
let lstm = nn::lstm(&vs / "lstm", input_size, hidden_size, Default::default());
let linear = nn::linear(&vs / "linear", hidden_size, output_size, Default::default());
let model = Sequential::new()
.add(lstm)
.add(linear);
model
}
// === Training ===
fn train_model(tokens: &[u8], vocab_size: i64) -> nn::Sequential {
let vs = nn::VarStore::new(Device::Cpu);
let hidden_size = 128;
let model = make_model(&vs.root(), vocab_size, hidden_size, vocab_size);
let mut opt = Optimizer::adam(&vs, 1e-3).unwrap();
let seq_len = 10;
for epoch in 0..10 {
for chunk in tokens.chunks(seq_len + 1) {
let input = Tensor::of_slice(chunk[..seq_len].as_ref())
.view([-1, 1])
.to_kind(Kind::Int64);
let target = Tensor::of_slice(chunk[1..=seq_len].as_ref())
.view([-1, 1])
.to_kind(Kind::Int64);
let output = model.forward(&input);
let loss = output.cross_entropy_for_logits(&target);
opt.backward_step(&loss);
}
println!("Epoch {} completed", epoch);
}
model
}
// === Audio Generation ===
fn note_to_freq(note: u8) -> f32 {
440.0 * (2.0).powf((note as i32 - 69) as f32 / 12.0)
}
fn generate_sine_wave(freq: f32, duration_ms: u64) -> Vec<f32> {
let samples_per_channel = (SAMPLE_RATE * duration_ms / 1000) as usize;
let two_pi = 2.0 * std::f32::consts::PI;
(0..samples_per_channel)
.map(|i| {
let t = i as f32 / SAMPLE_RATE;
(two_pi * freq * t).sin()
})
.collect()
}
// === Audio Streaming ===
fn start_audio_stream(receiver: crossbeam_channel::Receiver<Vec<f32>>) {
let host = cpal::default_host();
let device = host.default_output_device().expect("No output device");
let config = device.default_output_format().unwrap();
let sample_format = config.sample_format();
let channels = config.channels as usize;
let event_loop = cpal::EventLoop::new();
let stream_id = device
.build_output_stream(&config, move |data| {
match sample_format {
cpal::SampleFormat::F32 => write_audio_data(data, &receiver, channels),
_ => unimplemented!(),
}
})
.unwrap();
stream_id.play().unwrap();
std::mem::forget(stream_id); // Keep stream alive
}
fn write_audio_data<T: cpal::Sample>(data: &mut [T], receiver: &crossbeam_channel::Receiver<Vec<f32>>, channels: usize) {
for sample in data.chunks_mut(channels) {
let mut val = 0.0;
if let Ok(buffer) = receiver.try_recv() {
*sample = buffer.iter()
.map(|v| T::from::<f32>(&v))
.collect();
}
}
}
// === Endless Generation ===
fn generate_and_send_audio(model: &nn::Sequential, vocab_size: i64, sender: Sender<Vec<f32>>) {
let mut current_token = 0; // Start token
loop {
let input = Tensor::from(current_token).view([1, 1]);
let output = model.forward(&input);
let probs = output.softmax(-1, Kind::Float);
current_token = sample_from_probs(&probs, vocab_size);
let freq = note_to_freq(current_token as u8);
let samples = generate_sine_wave(freq, DURATION_MS);
sender.send(samples).unwrap();
}
}
fn sample_from_probs(probs: &Tensor, vocab_size: i64) -> i64 {
let probs_vec = probs.copy_to_slice(vocab_size as usize);
let total: f64 = probs_vec.iter().sum();
let rand_val: f64 = fastrand::f64() * total;
let mut sum = 0.0;
for (i, &p) in probs_vec.iter().enumerate() {
sum += p;
if sum >= rand_val {
return i as i64;
}
}
0
}
Notes:
- MIDI Parsing: This example only handles
NoteOn events and ignores timing. Real implementations should handle delta times and polyphony.
- Model Limitations: The LSTM is minimal and may not produce meaningful output without extensive training and tuning.
- Audio Streaming: Uses basic sine waves and assumes stereo output. Real-world use would need proper mixing and envelope shaping.
- Concurrency: Uses channels to communicate between threads but lacks error handling for simplicity.
This script provides a foundational structure. Practical applications would require enhancements in MIDI handling, model complexity, and audio processing.