Store the TTS object in the struct.

This commit is contained in:
Nolan Darilek 2020-12-29 15:45:56 -06:00
parent 965bea0adf
commit da8260cba8
2 changed files with 28 additions and 15 deletions

View File

@ -1,7 +1,9 @@
#[cfg(target_os = "android")] #[cfg(target_os = "android")]
use std::collections::HashMap;
use std::sync::Mutex; use std::sync::Mutex;
use jni::objects::JValue; use jni::objects::GlobalRef;
use jni::JavaVM;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use log::info; use log::info;
@ -9,11 +11,13 @@ use crate::{Backend, BackendId, Error, Features, UtteranceId, CALLBACKS};
lazy_static! { lazy_static! {
static ref NEXT_BACKEND_ID: Mutex<u64> = Mutex::new(0); static ref NEXT_BACKEND_ID: Mutex<u64> = Mutex::new(0);
static ref VM: Mutex<Option<JavaVM>> = Mutex::new(None);
} }
#[derive(Clone, Debug)] #[derive(Clone)]
pub(crate) struct Android { pub(crate) struct Android {
id: BackendId, id: BackendId,
tts: GlobalRef,
} }
impl Android { impl Android {
@ -23,18 +27,27 @@ impl Android {
let id = BackendId::Android(*backend_id); let id = BackendId::Android(*backend_id);
*backend_id += 1; *backend_id += 1;
let native_activity = ndk_glue::native_activity(); let native_activity = ndk_glue::native_activity();
let vm_ptr = native_activity.vm(); let mut vm = VM.lock().unwrap();
let vm = unsafe { jni::JavaVM::from_raw(vm_ptr) }?; if vm.is_none() {
let env = vm.attach_current_thread()?; let vm_ptr = native_activity.vm();
let tts = env.new_object( let new_vm = unsafe { jni::JavaVM::from_raw(vm_ptr) }?;
"android/speech/tts/TextToSpeech", *vm = Some(new_vm);
"(Landroid/content/Context;Landroid/speech/tts/TextToSpeech$OnInitListener;)V", }
&[ if let Some(vm) = &*vm {
native_activity.activity().into(), let env = vm.attach_current_thread()?;
native_activity.activity().into(), let tts = env.new_object(
], "android/speech/tts/TextToSpeech",
)?; "(Landroid/content/Context;Landroid/speech/tts/TextToSpeech$OnInitListener;)V",
Ok(Self { id }) &[
native_activity.activity().into(),
native_activity.activity().into(),
],
)?;
let tts = env.new_global_ref(tts)?;
Ok(Self { id, tts })
} else {
Err(Error::NoneError)
}
} }
} }

View File

@ -121,7 +121,7 @@ pub enum Error {
} }
#[clonable] #[clonable]
trait Backend: Clone + std::fmt::Debug { trait Backend: Clone {
fn id(&self) -> Option<BackendId>; fn id(&self) -> Option<BackendId>;
fn supported_features(&self) -> Features; fn supported_features(&self) -> Features;
fn speak(&mut self, text: &str, interrupt: bool) -> Result<Option<UtteranceId>, Error>; fn speak(&mut self, text: &str, interrupt: bool) -> Result<Option<UtteranceId>, Error>;