wavy/
microphone.rs

1// Wavy
2// Copyright © 2019-2021 Jeron Aldaron Lau.
3//
4// Licensed under any of:
5// - Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
6// - MIT License (https://mit-license.org/)
7// - Boost Software License, Version 1.0 (https://www.boost.org/LICENSE_1_0.txt)
8// At your choosing (See accompanying files LICENSE_APACHE_2_0.txt,
9// LICENSE_MIT.txt and LICENSE_BOOST_1_0.txt).
10
11use std::fmt::{Debug, Display, Formatter, Result};
12
13use fon::{chan::Ch32, Frame, Stream};
14
15use crate::ffi;
16
17/// Record audio samples from a microphone.
18#[derive(Default)]
19pub struct Microphone(pub(super) ffi::Microphone);
20
21impl Display for Microphone {
22    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
23        self.0.fmt(f)
24    }
25}
26
27impl Debug for Microphone {
28    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
29        <Self as Display>::fmt(self, f)
30    }
31}
32
33impl Microphone {
34    /// Query available audio sources.
35    pub fn query() -> Vec<Self> {
36        ffi::device_list(Self)
37    }
38
39    /// Check is microphone is available to use in a specific configuration
40    pub fn supports<F>(&self) -> bool
41    where
42        F: Frame<Chan = Ch32>,
43    {
44        let count = F::CHAN_COUNT;
45        let bit = count - 1;
46        (self.0.channels() & (1 << bit)) != 0
47    }
48
49    /// Record audio from connected microphone.  Returns an audio stream, which
50    /// contains the samples recorded since the previous call.
51    pub async fn record<F: Frame<Chan = Ch32>>(
52        &mut self,
53    ) -> MicrophoneStream<'_, F> {
54        (&mut self.0).await;
55        MicrophoneStream(self.0.record())
56    }
57}
58
59/// A stream of recorded audio samples from a microphone.
60pub struct MicrophoneStream<'a, F: Frame<Chan = Ch32>>(
61    ffi::MicrophoneStream<'a, F>,
62);
63
64impl<F: Frame<Chan = Ch32>> Debug for MicrophoneStream<'_, F> {
65    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
66        write!(fmt, "MicrophoneStream(rate: {:?})", self.sample_rate())
67    }
68}
69
70impl<F: Frame<Chan = Ch32>> Iterator for MicrophoneStream<'_, F> {
71    type Item = F;
72
73    fn next(&mut self) -> Option<Self::Item> {
74        self.0.next()
75    }
76}
77
78impl<F: Frame<Chan = Ch32>> Stream<F> for MicrophoneStream<'_, F> {
79    fn sample_rate(&self) -> Option<f64> {
80        self.0.sample_rate()
81    }
82
83    fn len(&self) -> Option<usize> {
84        self.0.len()
85    }
86}