Write a rust program that generates random audio files with strange sounds and unusual…
- User
Write a rust program that generates random audio files with strange sounds and unusual audio patterns
- Assistant
Here is a Rust program that generates random audio files with strange sounds and unusual audio patterns. The program creates a WAV file by combining multiple sine waves with random frequencies and amplitudes, and it changes these parameters over time to produce evolving sounds.
rustuse hound; use rand::Rng; use std::f32::consts::PI; fn main() { // Configure the WAV file specifications let spec = hound::WavSpec { channels: 1, // Mono audio sample_rate: 44100, // CD-quality sample rate bits_per_sample: 16, // Bits per sample sample_format: hound::SampleFormat::Int, }; // Duration of the audio file in seconds let duration_secs = 5; let total_samples = spec.sample_rate * duration_secs; // Create a new WAV writer to write the audio data let mut writer = hound::WavWriter::create("random_sound.wav", spec).unwrap(); // Initialize random number generator let mut rng = rand::thread_rng(); let num_oscillators = 5; // Number of sine waves to combine let chunk_size = spec.sample_rate / 2; // Change parameters every half-second // Initialize frequency and amplitude vectors let mut freqs = vec![0.0; num_oscillators]; let mut amplitudes = vec![0.0; num_oscillators]; // Generate the audio samples for t in 0..total_samples { // Update frequencies and amplitudes every chunk_size samples if t % chunk_size == 0 { for i in 0..num_oscillators { // Random frequency between 20 Hz and 2000 Hz freqs[i] = rng.gen_range(20.0..2000.0); // Random amplitude scaled by the number of oscillators amplitudes[i] = rng.gen_range(0.0..1.0 / num_oscillators as f32); } } let time = t as f32 / spec.sample_rate as f32; // Generate the combined sample from all oscillators let mut sample = 0.0; for i in 0..num_oscillators { sample += amplitudes[i] * (2.0 * PI * freqs[i] * time).sin(); } // Optionally, add a small amount of random noise let noise = rng.gen_range(-0.05..0.05); sample += noise; // Ensure the sample stays within the valid range [-1.0, 1.0] sample = sample.clamp(-1.0, 1.0); // Convert the sample to a 16-bit integer let sample_i16 = (sample * i16::MAX as f32) as i16; // Write the sample to the WAV file writer.write_sample(sample_i16).unwrap(); } // Finalize the WAV file writer.finalize().unwrap(); println!("Random sound generated in 'random_sound.wav'"); }