ezk_audio/
sample_rate.rs

1use ezk::ValueRange;
2use std::time::Duration;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
5pub struct SampleRate(pub u32);
6
7impl SampleRate {
8    /// Calculate the duration for the given amount of samples (per channel)
9    #[must_use]
10    pub fn duration_for_samples(self, len: usize) -> Duration {
11        Duration::from_nanos((1_000_000_000 * len as u64) / u64::from(self.0))
12    }
13
14    /// List of common sample rates encountered in the wild
15    #[must_use]
16    pub const fn common() -> &'static [SampleRate] {
17        &COMMON_SAMPLE_RATES
18    }
19
20    #[must_use]
21    pub fn any() -> ValueRange<Self> {
22        ValueRange::AnyOf(vec![
23            // Add some good rates which should be picked when choosing an arbitrary sample rate
24            ValueRange::Value(SampleRate(48000)),
25            ValueRange::Value(SampleRate(44100)),
26            ValueRange::Value(SampleRate(32000)),
27            ValueRange::Value(SampleRate(16000)),
28            ValueRange::Value(SampleRate(8000)),
29            ValueRange::range(
30                *COMMON_SAMPLE_RATES.first().unwrap(),
31                *COMMON_SAMPLE_RATES.last().unwrap(),
32            ),
33        ])
34    }
35}
36
37const COMMON_SAMPLE_RATES: [SampleRate; 15] = [
38    SampleRate(5512),
39    SampleRate(8000),
40    SampleRate(11025),
41    SampleRate(16000),
42    SampleRate(22050),
43    SampleRate(32000),
44    SampleRate(44100),
45    SampleRate(48000),
46    SampleRate(64000),
47    SampleRate(88200),
48    SampleRate(96000),
49    SampleRate(176_400),
50    SampleRate(192_000),
51    SampleRate(352_800),
52    SampleRate(384_000),
53];