48 lines
1.1 KiB
Rust
48 lines
1.1 KiB
Rust
use tts::Tts;
|
|
|
|
/// Reads text aloud through the platform's speech backend, created on first use.
|
|
pub struct Speaker {
|
|
tts: Option<Tts>,
|
|
}
|
|
|
|
impl Default for Speaker {
|
|
fn default() -> Self {
|
|
Self::new()
|
|
}
|
|
}
|
|
|
|
impl Speaker {
|
|
pub fn new() -> Self {
|
|
Self { tts: None }
|
|
}
|
|
|
|
/// Speak the text, interrupting what this speaker is already saying.
|
|
pub fn speak(&mut self, text: &str) -> Result<(), tts::Error> {
|
|
let tts = match self.tts.as_ref() {
|
|
Some(tts) => tts,
|
|
None => self.tts.insert(Tts::default()?),
|
|
};
|
|
|
|
tts.speak(text, true)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Stop speaking; a speaker that never spoke is already silent.
|
|
pub fn stop(&mut self) -> Result<(), tts::Error> {
|
|
match self.tts.as_ref() {
|
|
Some(tts) => tts.stop()?,
|
|
None => return Ok(()),
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Best-effort speaking state; a speaker that never spoke is silent.
|
|
pub fn speaking(&self) -> bool {
|
|
self.tts
|
|
.as_ref()
|
|
.and_then(|tts| tts.is_speaking().ok())
|
|
.unwrap_or(false)
|
|
}
|
|
}
|