Skip to main content

natural_tts/models/
mod.rs

1#[cfg(feature = "coqui")]
2pub mod coqui;
3#[cfg(feature = "gtts")]
4pub mod gtts;
5#[cfg(feature = "meta")]
6pub mod meta;
7#[cfg(feature = "msedge")]
8pub mod msedge;
9#[cfg(feature = "parler")]
10pub mod parler;
11#[cfg(feature = "tts-rs")]
12pub mod tts_rs;
13
14use crate::{
15    utils::{play_wav_file, read_wav_file},
16    TtsError,
17};
18use hound::WavSpec;
19#[cfg(feature = "msedge")]
20use msedge_tts::tts::AudioMetadata;
21use rodio::{cpal::Sample, OutputStream, Sink};
22use std::{fs::File, path::PathBuf};
23
24pub enum AudioHandler {
25    Sink {
26        sink: Sink,
27        stream: OutputStream,
28    },
29    #[cfg(feature = "tts-rs")]
30    Tts,
31}
32
33impl Clone for AudioHandler {
34    fn clone(&self) -> Self {
35        match self {
36            Self::Sink { .. } => panic!("Sink cant be cloned"),
37            #[cfg(feature = "tts-rs")]
38            Self::Tts => Self::Tts,
39        }
40    }
41}
42
43impl From<(Sink, OutputStream)> for AudioHandler {
44    fn from(value: (Sink, OutputStream)) -> Self {
45        Self::Sink {
46            sink: value.0,
47            stream: value.1,
48        }
49    }
50}
51
52pub trait NaturalModelTrait {
53    type SynthesizeType: Sample + Send + hound::Sample;
54    fn save(&mut self, message: String, path: &PathBuf) -> Result<(), TtsError>;
55
56    fn start(&mut self, message: String, path: &PathBuf) -> Result<AudioHandler, TtsError> {
57        let _ = self.save(message.clone(), path);
58        Ok(AudioHandler::from(play_wav_file(path)?))
59    }
60
61    fn synthesize(
62        &mut self,
63        message: String,
64        path: &PathBuf,
65    ) -> Result<SynthesizedAudio<Self::SynthesizeType>, TtsError> {
66        let _ = self.save(message.clone(), path);
67        let rwf = read_wav_file(path)?;
68        Ok(rwf)
69    }
70}
71
72pub enum Spec {
73    Wav(WavSpec),
74    #[cfg(feature = "msedge")]
75    Synthesized(String, Vec<AudioMetadata>),
76    Unknown,
77}
78
79pub struct SynthesizedAudio<T: Sample> {
80    pub spec: Spec,
81    pub data: Vec<T>,
82    pub duration: Option<i32>,
83}
84
85impl<T: Sample> SynthesizedAudio<T> {
86    pub fn new(data: Vec<T>, spec: Spec, duration: Option<i32>) -> Self {
87        return Self {
88            data,
89            spec,
90            duration,
91        };
92    }
93}
94
95pub fn did_save(path: &PathBuf) -> Result<(), TtsError> {
96    let file = File::open(path);
97    match file {
98        Ok(_) => Ok(()),
99        Err(_) => Err(TtsError::NotSaved),
100    }
101}