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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use cpal::{
traits::{DeviceTrait, HostTrait},
Device, SampleRate, SupportedStreamConfig,
};
pub struct StreamConfig {
device: Device,
config: SupportedStreamConfig,
silence_level: i32,
}
#[cfg(test)]
mod tests {
use crate::config::get_config;
use cpal::traits::HostTrait;
#[test]
fn supported_device() {
let host = cpal::default_host();
let device = host.default_input_device().expect("no input device found");
assert_eq!(1, get_config(&device).channels());
}
}
impl StreamConfig {
pub fn new(silence_level: i32) -> Self {
let device = get_default_device();
StreamConfig {
config: get_config(&device),
device,
silence_level,
}
}
pub fn device(&self) -> &Device {
&self.device
}
pub fn config(&self) -> SupportedStreamConfig {
self.config.clone()
}
pub fn silence_level(&self) -> i32 {
self.silence_level
}
}
fn get_config(device: &Device) -> SupportedStreamConfig {
let mut config = device
.default_input_config()
.expect("Failed to get input config");
while config.channels() != 1 {
let mut supported_configs_range = device
.supported_input_configs()
.expect("error while querying configs");
config = match supported_configs_range.next() {
Some(conf) => conf.with_sample_rate(SampleRate(16000)),
None => break,
};
}
config
}
fn get_default_device() -> Device {
let host = cpal::default_host();
host.default_input_device().expect("no input device found")
}