Skip to main content

tauri_plugin_tts/
lib.rs

1use tauri::{
2    plugin::{Builder, TauriPlugin},
3    Manager, Runtime,
4};
5
6pub use models::*;
7
8#[cfg(desktop)]
9mod desktop;
10#[cfg(mobile)]
11mod mobile;
12
13mod commands;
14mod error;
15mod models;
16
17pub use error::{Error, Result};
18
19#[cfg(desktop)]
20use desktop::Tts;
21#[cfg(mobile)]
22use mobile::Tts;
23
24/// Extensions to [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`] to access the tts APIs.
25pub trait TtsExt<R: Runtime> {
26    fn tts(&self) -> &Tts<R>;
27}
28
29impl<R: Runtime, T: Manager<R>> crate::TtsExt<R> for T {
30    fn tts(&self) -> &Tts<R> {
31        self.state::<Tts<R>>().inner()
32    }
33}
34
35pub fn init<R: Runtime>() -> TauriPlugin<R> {
36    Builder::new("tts")
37        .invoke_handler(tauri::generate_handler![
38            commands::speak,
39            commands::stop,
40            commands::get_voices,
41            commands::is_speaking,
42            commands::is_initialized,
43            commands::pause_speaking,
44            commands::resume_speaking,
45            commands::preview_voice,
46            commands::set_background_behavior
47        ])
48        .setup(|app, api| {
49            #[cfg(mobile)]
50            {
51                let tts = mobile::init(app, api)?;
52                // Set up the relay channel that forwards native events through app.emit()
53                // so JS can use listen("tts://speech:finish") uniformly on all platforms.
54                if let Err(e) = tts.setup_event_relay(app) {
55                    log::warn!("TTS event relay setup failed: {e:?}");
56                }
57                app.manage(tts);
58            }
59            #[cfg(desktop)]
60            {
61                let tts = desktop::init(app, api)?;
62                app.manage(tts);
63            }
64            Ok(())
65        })
66        .build()
67}