■ WavWriter 구조체의 write_sample 메소드를 사용해 동요 WAV 파일을 생성하는 방법을 보여준다.
▶ Cargo.toml
1 2 3 4 5 6 7 8 9 10 11 |
[package] name = "test_project" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] hound = "3.4.0" |
▶ 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 62 |
use std::f32::consts; use std::fs; use std::io; use hound; const SAMPLE_RATE : f32 = 44100.0; const BPM : f32 = 122.0; // 템포 #[allow(unused_variables)] fn main() { let wav_spec : hound::WavSpec = hound::WavSpec { channels : 1, sample_rate : SAMPLE_RATE as u32, bits_per_sample : 16, sample_format : hound::SampleFormat::Int }; let mut wav_writer : hound::WavWriter<io::BufWriter<fs::File>> = hound::WavWriter::create("d:/melody.wav", wav_spec).unwrap(); // 음정 let c4 : f32 = 261.626; // 도 let d4 : f32 = 293.665; // 레 let e4 : f32 = 329.628; // 미 let f4 : f32 = 349.228; // 파 let g4 : f32 = 391.995; // 솔 let a4 : f32 = 440.000; // 라 let b4 : f32 = 493.883; // 시 let c5 : f32 = 523.251; // 도 // 음 길이 let l4 : u32 = ((60.0 / BPM) * SAMPLE_RATE) as u32; let l2 : u32 = l4 * 2; write_tone(&mut wav_writer, g4, l4); // 솔 write_tone(&mut wav_writer, g4, l4); // 솔 write_tone(&mut wav_writer, a4, l4); // 라 write_tone(&mut wav_writer, a4, l4); // 라 write_tone(&mut wav_writer, g4, l4); // 솔 write_tone(&mut wav_writer, g4, l4); // 솔 write_tone(&mut wav_writer, e4, l2); // 미 write_tone(&mut wav_writer, g4, l4); // 솔 write_tone(&mut wav_writer, g4, l4); // 솔 write_tone(&mut wav_writer, e4, l4); // 미 write_tone(&mut wav_writer, e4, l4); // 미 write_tone(&mut wav_writer, d4, l2); // 레 } fn write_tone<W>(wav_writer : &mut hound::WavWriter<W>, tone : f32, length : u32) where W : io::Write + io::Seek { for t in 0..length { let a : f32 = t as f32 / SAMPLE_RATE; let v : f32 = (a * tone * 2.0 * consts::PI).sin(); wav_writer.write_sample((v * i16::MAX as f32) as i16).unwrap(); } } |