■ WavWriter 구조체의 write_sample 메소드를 사용해 백색 잡음(white noise)의 WAV 파일을 생성하는 방법을 보여준다.
▶ Cargo.toml
1 2 3 4 5 6 7 8 9 10 |
[package] name = "test_project" version = "0.1.0" edition = "2021" [dependencies] hound = "3.4.0" rand = "0.8.4" |
▶ src/main.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
use std::fs; use std::io; use hound; use rand::prelude::*; const SAMPLE_RATE : f32 = 44100.0; fn main() { let wav_spec : hound::WavSpec = hound::WavSpec { channels : 1, sample_rate : SAMPLE_RATE as u32, bits_per_sample : 32, sample_format : hound::SampleFormat::Float }; let mut wave_writer : hound::WavWriter<io::BufWriter<fs::File>> = hound::WavWriter::create("d:/noise.wav", wav_spec).unwrap(); let mut wave_vector : Vec<f32> = vec![]; let bpm : usize = 120; wave_vector.extend(get_noise_wave_vector(2.0, -1.0, calculate_note_length(bpm, 2))); wave_vector.extend(get_noise_wave_vector(0.2, 0.8, calculate_note_length(bpm, 2))); wave_vector.extend(get_noise_wave_vector(0.8, -1.0, calculate_note_length(bpm, 2))); for value in wave_vector.into_iter() { wave_writer.write_sample(value).unwrap(); } } // bpm : 분당 박자, beats per minute // note : 음표 예) 4(4분 음표) fn calculate_note_length(bpm : usize, note: usize) -> usize { return ((4.0 / note as f32) * (60.0 / bpm as f32) * SAMPLE_RATE) as usize; } // range : 범위 // shift : 시프트 // note_length : 음표 길이 (샘플 수) fn get_noise_wave_vector(range : f32, shift : f32, note_length : usize) -> Vec<f32> { let mut wave_vector : Vec<f32> = vec![0.0; note_length]; let mut thread_rng : ThreadRng = rand::thread_rng(); for i in 0..note_length { wave_vector[i] = thread_rng.gen::<f32>() * range + shift; } let gain : f32 = 0.5; return wave_vector.into_iter().map(|v : f32| (v * gain) as f32).collect(); } |