diff --git a/android/src/main/java/com/getcapacitor/community/tts/TextToSpeech.java b/android/src/main/java/com/getcapacitor/community/tts/TextToSpeech.java index 3ad76834dca58c126baa8f5edf3ab062c73ad11b..73660625e2570c99f20abb8e32dd350bbbd5ed5d 100644 --- a/android/src/main/java/com/getcapacitor/community/tts/TextToSpeech.java +++ b/android/src/main/java/com/getcapacitor/community/tts/TextToSpeech.java @@ -1,5 +1,7 @@ package com.getcapacitor.community.tts; +import android.app.Activity; +import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; @@ -22,6 +24,19 @@ public class TextToSpeech implements android.speech.tts.TextToSpeech.OnInitListe public static final String LOG_TAG = "TextToSpeech"; + /** + * EO Nexus patch: the name ending of Google's per-locale alias voice ("ja-JP-language"). It + * reports no network requirement, yet the engine picks the voice behind it per request: with the + * Japanese data missing it synthesised through "ja-jp-x-jab-server". Never counted as on-device. + */ + private static final String LOCALE_ALIAS_SUFFIX = "-language"; + + /** + * EO Nexus patch: the system text-to-speech settings screen. Not an SDK constant: the action + * AOSP Settings declares for its exported TextToSpeechSettingsActivity. + */ + private static final String ACTION_TTS_SETTINGS = "com.android.settings.TTS_SETTINGS"; + private Context context; private android.speech.tts.TextToSpeech tts = null; private int initializationStatus; @@ -55,6 +70,16 @@ public class TextToSpeech implements android.speech.tts.TextToSpeech.OnInitListe } } + /** + * EO Nexus patch: log which engine error it was (TextToSpeech.ERROR_*, e.g. -9 + * ERROR_NOT_INSTALLED_YET), then fail the request exactly as before. + */ + @Override + public void onError(String utteranceId, int errorCode) { + Log.w(LOG_TAG, "Utterance " + utteranceId + " failed: engine error " + errorCode); + onError(utteranceId); + } + @Override public void onRangeStart(String utteranceId, int start, int end, int frame) { SpeakResultCallback callback = requests.get(utteranceId); @@ -123,6 +148,80 @@ public class TextToSpeech implements android.speech.tts.TextToSpeech.OnInitListe tts.speak(text, queueStrategy, ttsParams, callbackId); } + /** + * EO Nexus patch: speak only with the voice at {@code voice}, and only if it synthesises on the + * device. Returns false — having queued nothing and flushed nothing — when that voice is missing, + * needs a network connection, still has data to download, is the engine's per-locale alias, or + * is not the voice the engine reports once {@code setVoice} has returned SUCCESS. The language + * comes from the voice: {@code setLanguage} is not called, as it loads the locale's default + * voice, which can be a network one or start a data download. + */ + @SuppressWarnings("deprecation") + public boolean speakOnDevice( + String text, + float rate, + float pitch, + float volume, + int voice, + String callbackId, + SpeakResultCallback resultCallback, + int queueStrategy + ) { + Voice chosen = onDeviceVoiceAt(voice); + if (chosen == null) { + return false; + } + if (tts.setVoice(chosen) != android.speech.tts.TextToSpeech.SUCCESS) { + return false; + } + Voice active = tts.getVoice(); + if (active == null || !chosen.getName().equals(active.getName()) || !isOnDevice(active)) { + return false; + } + + if (queueStrategy != android.speech.tts.TextToSpeech.QUEUE_ADD) { + stop(); + } + requests.put(callbackId, resultCallback); + + Bundle ttsParams = new Bundle(); + ttsParams.putSerializable(android.speech.tts.TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackId); + ttsParams.putSerializable(android.speech.tts.TextToSpeech.Engine.KEY_PARAM_VOLUME, volume); + // Deprecated since API 21 in favour of choosing the voice, done above. Still sent, as the + // framework passes them on (as Boolean or String) to engines that read them. + ttsParams.putString(android.speech.tts.TextToSpeech.Engine.KEY_FEATURE_EMBEDDED_SYNTHESIS, "true"); + ttsParams.putString(android.speech.tts.TextToSpeech.Engine.KEY_FEATURE_NETWORK_SYNTHESIS, "false"); + + tts.setSpeechRate(rate); + tts.setPitch(pitch); + tts.speak(text, queueStrategy, ttsParams, callbackId); + return true; + } + + /** EO Nexus patch: the voice at {@code index} of the ordered list, if it is on-device. */ + private Voice onDeviceVoiceAt(int index) { + if (index < 0) { + return null; + } + ArrayList voices = getSupportedVoicesOrdered(); + if (index >= voices.size()) { + return null; + } + Voice voice = voices.get(index); + return isOnDevice(voice) ? voice : null; + } + + /** EO Nexus patch: no network connection, its data installed, and not the per-locale alias. */ + private static boolean isOnDevice(Voice voice) { + return !voice.isNetworkConnectionRequired() && !isNotInstalled(voice) && !voice.getName().endsWith(LOCALE_ALIAS_SUFFIX); + } + + /** EO Nexus patch: the voice still has data to download. Unknown features count as not installed. */ + private static boolean isNotInstalled(Voice voice) { + Set features = voice.getFeatures(); + return features == null || features.contains(android.speech.tts.TextToSpeech.Engine.KEY_FEATURE_NOT_INSTALLED); + } + public void stop() { tts.stop(); requests.clear(); @@ -166,16 +265,37 @@ public class TextToSpeech implements android.speech.tts.TextToSpeech.OnInitListe return result; } - public void openInstall() { - PackageManager packageManager = context.getPackageManager(); - Intent installIntent = new Intent(); - installIntent.setAction(android.speech.tts.TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); - - ResolveInfo resolveInfo = packageManager.resolveActivity(installIntent, PackageManager.MATCH_DEFAULT_ONLY); + /** + * EO Nexus patch: open a screen where voice data can be added, and say whether one started. + * First the default engine's own installer — ACTION_INSTALL_TTS_DATA sent to that engine's + * package, as the system's text-to-speech settings send it — then the system text-to-speech + * settings. Each is started and its failure caught, rather than asked about first: from Android + * 11 resolveActivity() is filtered by package visibility, starting an activity is not. Not + * ACTION_CHECK_TTS_DATA, which returns a result to its caller and shows nothing. + */ + public boolean openInstall() { + String engine = tts == null ? null : tts.getDefaultEngine(); + if (engine != null && !engine.isEmpty()) { + Intent install = new Intent(android.speech.tts.TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); + install.setPackage(engine); + if (startScreen(install)) { + return true; + } + } + return startScreen(new Intent(ACTION_TTS_SETTINGS)); + } - if (resolveInfo != null) { - installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(installIntent); + /** EO Nexus patch: start the screen {@code intent} names, or report that it could not start. */ + private boolean startScreen(Intent intent) { + if (!(context instanceof Activity)) { + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + try { + context.startActivity(intent); + return true; + } catch (ActivityNotFoundException | SecurityException ex) { + Log.w(LOG_TAG, "Could not start " + intent.getAction(), ex); + return false; } } @@ -208,6 +328,9 @@ public class TextToSpeech implements android.speech.tts.TextToSpeech.OnInitListe obj.put("lang", locale.toLanguageTag()); obj.put("localService", !voice.isNetworkConnectionRequired()); obj.put("default", false); + // EO Nexus patch: what speakOnDevice() checks, so the app can choose before it asks. + obj.put("networkRequired", voice.isNetworkConnectionRequired()); + obj.put("notInstalled", isNotInstalled(voice)); return obj; } } diff --git a/android/src/main/java/com/getcapacitor/community/tts/TextToSpeechPlugin.java b/android/src/main/java/com/getcapacitor/community/tts/TextToSpeechPlugin.java index 62eaf01719fce634865593515eb8c8a908109df5..3402e90b95ecc846a10a3f47edd198d9b82752b3 100644 --- a/android/src/main/java/com/getcapacitor/community/tts/TextToSpeechPlugin.java +++ b/android/src/main/java/com/getcapacitor/community/tts/TextToSpeechPlugin.java @@ -16,6 +16,19 @@ public class TextToSpeechPlugin extends Plugin { public static final String ERROR_UTTERANCE = "Failed to read text."; public static final String ERROR_UNSUPPORTED_LANGUAGE = "This language is not supported."; + /** EO Nexus patch: why a speak with requireOnDevice was refused, and the code it carries. */ + public static final String ERROR_ON_DEVICE_VOICE_UNAVAILABLE = "No voice on this device can speak this without a network connection."; + public static final String CODE_ON_DEVICE_VOICE_UNAVAILABLE = "ON_DEVICE_VOICE_UNAVAILABLE"; + /** + * EO Nexus patch: the code a speak with requireOnDevice is rejected with when the engine took + * the on-device voice and then failed to synthesise with it (UtteranceProgressListener.onError). + * Google's engine does that the first time it uses a voice whose data it is still fetching. The + * message stays ERROR_UTTERANCE. + */ + public static final String CODE_ON_DEVICE_SYNTHESIS_FAILED = "ON_DEVICE_SYNTHESIS_FAILED"; + /** EO Nexus patch: why openInstall was rejected — no screen to add voice data could start. */ + public static final String ERROR_INSTALL_SCREEN_UNAVAILABLE = "No screen to add voice data or change text-to-speech settings could be opened."; + public static final String CODE_INSTALL_SCREEN_UNAVAILABLE = "INSTALL_SCREEN_UNAVAILABLE"; private TextToSpeech implementation; @@ -39,6 +52,7 @@ public class TextToSpeechPlugin extends Plugin { float volume = call.getFloat("volume", 1.0f); int voice = call.getInt("voice", -1); int queueStrategy = call.getInt("queueStrategy", 0); + boolean requireOnDevice = Boolean.TRUE.equals(call.getBoolean("requireOnDevice", false)); boolean isLanguageSupported = implementation.isLanguageSupported(lang); if (!isLanguageSupported) { @@ -54,7 +68,12 @@ public class TextToSpeechPlugin extends Plugin { @Override public void onError() { - call.reject(ERROR_UTTERANCE); + // EO Nexus patch: an on-device speak the engine failed says so with a code of its own. + if (requireOnDevice) { + call.reject(ERROR_UTTERANCE, CODE_ON_DEVICE_SYNTHESIS_FAILED); + } else { + call.reject(ERROR_UTTERANCE); + } } @Override @@ -69,6 +88,13 @@ public class TextToSpeechPlugin extends Plugin { }; try { + if (requireOnDevice) { + // EO Nexus patch: synthesised on the device, or not spoken at all. + if (!implementation.speakOnDevice(text, rate, pitch, volume, voice, call.getCallbackId(), resultCallback, queueStrategy)) { + call.reject(ERROR_ON_DEVICE_VOICE_UNAVAILABLE, CODE_ON_DEVICE_VOICE_UNAVAILABLE); + } + return; + } implementation.speak(text, lang, rate, pitch, volume, voice, call.getCallbackId(), resultCallback, queueStrategy); } catch (Exception ex) { call.reject(ex.getLocalizedMessage()); @@ -130,7 +156,11 @@ public class TextToSpeechPlugin extends Plugin { @PluginMethod public void openInstall(PluginCall call) { try { - implementation.openInstall(); + // EO Nexus patch: say so when neither the installer nor the settings screen started. + if (!implementation.openInstall()) { + call.reject(ERROR_INSTALL_SCREEN_UNAVAILABLE, CODE_INSTALL_SCREEN_UNAVAILABLE); + return; + } call.resolve(); } catch (Exception ex) { call.reject(ex.getLocalizedMessage()); diff --git a/dist/esm/definitions.d.ts b/dist/esm/definitions.d.ts index b763f724cbb5d864142e72f67ef81de631ad8e9b..c8793e1aad356d54099bae72fc65322eaea2bd98 100644 --- a/dist/esm/definitions.d.ts +++ b/dist/esm/definitions.d.ts @@ -31,6 +31,10 @@ export interface TextToSpeechPlugin { /** * Verifies proper installation and availability of resource files on the system. * + * EO Nexus patch: opens the default engine's screen that installs voice data + * (`ACTION_INSTALL_TTS_DATA`), or the system text-to-speech settings when that cannot start. + * Rejected with the code `INSTALL_SCREEN_UNAVAILABLE` when neither could be opened. + * * Only available for Android. */ openInstall(): Promise; @@ -104,6 +108,19 @@ export interface TTSOptions { * @default QueueStrategy.Flush */ queueStrategy?: QueueStrategy; + /** + * EO Nexus patch. Speak only with the voice at `voice`, and only if it synthesises on the + * device: no network connection, its data installed, not the engine's per-locale alias, and + * the voice the engine reports once it is set. Otherwise nothing is spoken and the call is + * rejected with the code `ON_DEVICE_VOICE_UNAVAILABLE`. A speak the engine takes and then + * fails to synthesise (as when it is still fetching the voice's data) is rejected with + * `Failed to read text.` and the code `ON_DEVICE_SYNTHESIS_FAILED`. + * + * Only available for Android; ignored on web and iOS. + * + * @default false + */ + requireOnDevice?: boolean; } /** * The SpeechSynthesisVoice interface represents a voice that the system supports. @@ -139,4 +156,17 @@ export interface SpeechSynthesisVoice { * @example "urn:moz-tts:sapi:Microsoft Zira Desktop - English (United States)?en-US" */ voiceURI: string; + /** + * EO Nexus patch. Whether the voice needs a network connection (`Voice.isNetworkConnectionRequired()`). + * + * Only available for Android. + */ + networkRequired?: boolean; + /** + * EO Nexus patch. Whether the voice still has data to download (`Voice.getFeatures()` holds + * `TextToSpeech.Engine.KEY_FEATURE_NOT_INSTALLED`, or cannot be read). + * + * Only available for Android. + */ + notInstalled?: boolean; }