Created
October 7, 2024 17:34
-
-
Save codegod100/8e40fd93497d628fd68e45f9d272f4c9 to your computer and use it in GitHub Desktop.
mario generated from ai
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use tracing::debug; | |
fn main() { | |
tracing_subscriber::fmt::init(); | |
let spec = hound::WavSpec { | |
channels: 1, | |
sample_rate: 44100, | |
bits_per_sample: 16, | |
sample_format: hound::SampleFormat::Int, | |
}; | |
// Create a buffer of 32 random bytes | |
// Mario theme song notes and durations (first measure) | |
let notes = vec![ | |
(660, 100), | |
(0, 25), | |
(660, 100), | |
(0, 25), | |
(0, 100), | |
(660, 100), | |
(0, 25), | |
(523, 100), | |
(660, 100), | |
(0, 25), | |
(784, 100), | |
(0, 300), | |
(392, 100), | |
(0, 300), | |
]; | |
let sample_rate = spec.sample_rate as f32; | |
let mut buffer = Vec::new(); | |
// Tempo adjustment factor (increase this to slow down the tempo) | |
let tempo_factor = 1.5; | |
for (frequency, duration) in notes { | |
let adjusted_duration = (duration as f32 * tempo_factor) as usize; | |
let num_samples = (sample_rate * adjusted_duration as f32 / 1000.0) as usize; | |
for i in 0..num_samples { | |
let t = i as f32 / sample_rate; | |
let mut sample = if (t * frequency as f32 * 2.0).sin() > 0.0 { | |
1.0 | |
} else { | |
-1.0 | |
}; | |
// Apply a simple envelope | |
let attack = 0.005 * tempo_factor; | |
let release = 0.05 * tempo_factor; | |
let note_duration = adjusted_duration as f32 / 1000.0; | |
let envelope = if t < attack { | |
t / attack | |
} else if t > note_duration - release { | |
(note_duration - t) / release | |
} else { | |
1.0 | |
}; | |
sample *= envelope; | |
buffer.push((sample * i16::MAX as f32 * 0.5) as i16); // Reduce volume to 50% | |
} | |
} | |
// Add a short silence at the end | |
let silence_duration = 0.1; | |
let silence_samples = (sample_rate * silence_duration) as usize; | |
buffer.extend(std::iter::repeat(0).take(silence_samples)); | |
let mut writer = hound::WavWriter::create("mario.wav", spec).unwrap(); | |
for &sample in &buffer { | |
debug!(sample); | |
writer.write_sample(sample).unwrap(); | |
} | |
writer.finalize().unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment