| 1 | use std::f32::consts::PI; |
| 2 | |
| 3 | pub const SAMPLE_RATE: u32 = 44_100; |
| 4 | const LOW_HZ: f32 = 784.; |
| 5 | const HIGH_HZ: f32 = 988.; |
| 6 | const BEEP_SECONDS: f32 = 0.18; |
| 7 | const FADE_SECONDS: f32 = 0.015; |
| 8 | const AMPLITUDE: f32 = 0.3; |
| 9 | const BEEPS: [f32; 4] = [LOW_HZ, HIGH_HZ, LOW_HZ, HIGH_HZ]; |
| 10 | const CYCLE_SECONDS: f32 = 2.4; |
| 11 | |
| 12 | pub fn ring_cycle(sample_rate: u32) -> Vec<f32> { |
| 13 | let total = (CYCLE_SECONDS * sample_rate as f32) as usize; |
| 14 | let beep = (BEEP_SECONDS * sample_rate as f32) as usize; |
| 15 | let fade = (FADE_SECONDS * sample_rate as f32) as usize; |
| 16 | let mut samples = vec![0.; total]; |
| 17 | for (index, frequency) in BEEPS.iter().enumerate() { |
| 18 | let start = index * beep; |
| 19 | for position in 0..beep { |
| 20 | let envelope = (position.min(beep - 1 - position) as f32 / fade as f32).min(1.); |
| 21 | let phase = 2. * PI * frequency * position as f32 / sample_rate as f32; |
| 22 | samples[start + position] = AMPLITUDE * envelope * phase.sin(); |
| 23 | } |
| 24 | } |
| 25 | samples |
| 26 | } |
| 27 | |
| 28 | #[cfg(test)] |
| 29 | mod tests { |
| 30 | use super::*; |
| 31 | |
| 32 | #[test] |
| 33 | fn a_cycle_lasts_two_and_a_half_seconds_at_most_and_stays_quiet() { |
| 34 | let samples = ring_cycle(SAMPLE_RATE); |
| 35 | assert_eq!(samples.len(), (CYCLE_SECONDS * SAMPLE_RATE as f32) as usize); |
| 36 | assert!(samples.iter().all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON)); |
| 37 | assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9)); |
| 38 | } |
| 39 | |
| 40 | #[test] |
| 41 | fn beeps_fade_in_and_out_without_clicks() { |
| 42 | let samples = ring_cycle(SAMPLE_RATE); |
| 43 | assert_eq!(samples[0], 0.); |
| 44 | let beep = (BEEP_SECONDS * SAMPLE_RATE as f32) as usize; |
| 45 | assert!(samples[1].abs() < 0.05); |
| 46 | assert!(samples[beep - 1].abs() < 0.05); |
| 47 | } |
| 48 | |
| 49 | #[test] |
| 50 | fn the_cycle_ends_in_silence_so_it_can_repeat() { |
| 51 | let samples = ring_cycle(SAMPLE_RATE); |
| 52 | let beeps_end = (BEEP_SECONDS * BEEPS.len() as f32 * SAMPLE_RATE as f32) as usize; |
| 53 | assert!(samples[beeps_end..].iter().all(|sample| *sample == 0.)); |
| 54 | assert!(beeps_end < samples.len()); |
| 55 | } |
| 56 | |
| 57 | #[test] |
| 58 | fn the_cycle_is_the_same_every_time() { |
| 59 | assert_eq!(ring_cycle(SAMPLE_RATE), ring_cycle(SAMPLE_RATE)); |
| 60 | } |
| 61 | } |