TextToSpeechpublic class TextToSpeech extends Object Synthesizes speech from text for immediate playback or to create a sound file.
A TextToSpeech instance can only be used to synthesize text once it has completed its
initialization. Implement the {@link TextToSpeech.OnInitListener} to be
notified of the completion of the initialization.
When you are done using the TextToSpeech instance, call the {@link #shutdown()} method
to release the native resources used by the TextToSpeech engine. |
Fields Summary |
---|
private static final String | TAG | public static final int | SUCCESSDenotes a successful operation. | public static final int | ERRORDenotes a generic operation failure. | public static final int | STOPPEDDenotes a stop requested by a client. It's used only on the service side of the API,
client should never expect to see this result code. | public static final int | ERROR_SYNTHESISDenotes a failure of a TTS engine to synthesize the given input. | public static final int | ERROR_SERVICEDenotes a failure of a TTS service. | public static final int | ERROR_OUTPUTDenotes a failure related to the output (audio device or a file). | public static final int | ERROR_NETWORKDenotes a failure caused by a network connectivity problems. | public static final int | ERROR_NETWORK_TIMEOUTDenotes a failure caused by network timeout. | public static final int | ERROR_INVALID_REQUESTDenotes a failure caused by an invalid request. | public static final int | ERROR_NOT_INSTALLED_YETDenotes a failure caused by an unfinished download of the voice data. | public static final int | QUEUE_FLUSHQueue mode where all entries in the playback queue (media to be played
and text to be synthesized) are dropped and replaced by the new entry.
Queues are flushed with respect to a given calling app. Entries in the queue
from other callees are not discarded. | public static final int | QUEUE_ADDQueue mode where the new entry is added at the end of the playback queue. | static final int | QUEUE_DESTROYQueue mode where the entire playback queue is purged. This is different
from {@link #QUEUE_FLUSH} in that all entries are purged, not just entries
from a given caller. | public static final int | LANG_COUNTRY_VAR_AVAILABLEDenotes the language is available exactly as specified by the locale. | public static final int | LANG_COUNTRY_AVAILABLEDenotes the language is available for the language and country specified
by the locale, but not the variant. | public static final int | LANG_AVAILABLEDenotes the language is available for the language by the locale,
but not the country and variant. | public static final int | LANG_MISSING_DATADenotes the language data is missing. | public static final int | LANG_NOT_SUPPORTEDDenotes the language is not supported. | public static final String | ACTION_TTS_QUEUE_PROCESSING_COMPLETEDBroadcast Action: The TextToSpeech synthesizer has completed processing
of all the text in the speech queue.
Note that this notifies callers when the engine has finished has
processing text data. Audio playback might not have completed (or even started)
at this point. If you wish to be notified when this happens, see
{@link OnUtteranceCompletedListener}. | private final android.content.Context | mContext | private Connection | mConnectingServiceConnection | private Connection | mServiceConnection | private OnInitListener | mInitListener | private volatile UtteranceProgressListener | mUtteranceProgressListener | private final Object | mStartLock | private String | mRequestedEngine | private final boolean | mUseFallback | private final Map | mEarcons | private final Map | mUtterances | private final android.os.Bundle | mParams | private final TtsEngines | mEnginesHelper | private volatile String | mCurrentEngine |
Constructors Summary |
---|
public TextToSpeech(android.content.Context context, OnInitListener listener)The constructor for the TextToSpeech class, using the default TTS engine.
This will also initialize the associated TextToSpeech engine if it isn't already running.
this(context, listener, null);
| public TextToSpeech(android.content.Context context, OnInitListener listener, String engine)The constructor for the TextToSpeech class, using the given TTS engine.
This will also initialize the associated TextToSpeech engine if it isn't already running.
this(context, listener, engine, null, true);
| public TextToSpeech(android.content.Context context, OnInitListener listener, String engine, String packageName, boolean useFallback)Used by the framework to instantiate TextToSpeech objects with a supplied
package name, instead of using {@link android.content.Context#getPackageName()}
mContext = context;
mInitListener = listener;
mRequestedEngine = engine;
mUseFallback = useFallback;
mEarcons = new HashMap<String, Uri>();
mUtterances = new HashMap<CharSequence, Uri>();
mUtteranceProgressListener = null;
mEnginesHelper = new TtsEngines(mContext);
initTts();
|
Methods Summary |
---|
public int | addEarcon(java.lang.String earcon, java.lang.String packagename, int resourceId)Adds a mapping between a string of text and a sound resource in a
package. Use this to add custom earcons.
synchronized(mStartLock) {
mEarcons.put(earcon, makeResourceUri(packagename, resourceId));
return SUCCESS;
}
| public int | addEarcon(java.lang.String earcon, java.lang.String filename)Adds a mapping between a string of text and a sound file.
Use this to add custom earcons.
synchronized(mStartLock) {
mEarcons.put(earcon, Uri.parse(filename));
return SUCCESS;
}
| public int | addEarcon(java.lang.String earcon, java.io.File file)Adds a mapping between a string of text and a sound file.
Use this to add custom earcons.
synchronized(mStartLock) {
mEarcons.put(earcon, Uri.fromFile(file));
return SUCCESS;
}
| public int | addSpeech(java.lang.String text, java.lang.String packagename, int resourceId)Adds a mapping between a string of text and a sound resource in a
package. After a call to this method, subsequent calls to
{@link #speak(String, int, HashMap)} will play the specified sound resource
if it is available, or synthesize the text it is missing.
synchronized (mStartLock) {
mUtterances.put(text, makeResourceUri(packagename, resourceId));
return SUCCESS;
}
| public int | addSpeech(java.lang.CharSequence text, java.lang.String packagename, int resourceId)Adds a mapping between a CharSequence (may be spanned with TtsSpans) of text
and a sound resource in a package. After a call to this method, subsequent calls to
{@link #speak(String, int, HashMap)} will play the specified sound resource
if it is available, or synthesize the text it is missing.
synchronized (mStartLock) {
mUtterances.put(text, makeResourceUri(packagename, resourceId));
return SUCCESS;
}
| public int | addSpeech(java.lang.String text, java.lang.String filename)Adds a mapping between a string of text and a sound file. Using this, it
is possible to add custom pronounciations for a string of text.
After a call to this method, subsequent calls to {@link #speak(String, int, HashMap)}
will play the specified sound resource if it is available, or synthesize the text it is
missing.
synchronized (mStartLock) {
mUtterances.put(text, Uri.parse(filename));
return SUCCESS;
}
| public int | addSpeech(java.lang.CharSequence text, java.io.File file)Adds a mapping between a CharSequence (may be spanned with TtsSpans and a sound file.
Using this, it is possible to add custom pronounciations for a string of text.
After a call to this method, subsequent calls to {@link #speak(String, int, HashMap)}
will play the specified sound resource if it is available, or synthesize the text it is
missing.
synchronized (mStartLock) {
mUtterances.put(text, Uri.fromFile(file));
return SUCCESS;
}
| public boolean | areDefaultsEnforced()Checks whether the user's settings should override settings requested
by the calling application. As of the Ice cream sandwich release,
user settings never forcibly override the app's settings.
return false;
| private boolean | connectToEngine(java.lang.String engine)
Connection connection = new Connection();
Intent intent = new Intent(Engine.INTENT_ACTION_TTS_SERVICE);
intent.setPackage(engine);
boolean bound = mContext.bindService(intent, connection, Context.BIND_AUTO_CREATE);
if (!bound) {
Log.e(TAG, "Failed to bind to " + engine);
return false;
} else {
Log.i(TAG, "Sucessfully bound to " + engine);
mConnectingServiceConnection = connection;
return true;
}
| private android.os.Bundle | convertParamsHashMaptoBundle(java.util.HashMap params)
if (params != null && !params.isEmpty()) {
Bundle bundle = new Bundle();
copyIntParam(bundle, params, Engine.KEY_PARAM_STREAM);
copyIntParam(bundle, params, Engine.KEY_PARAM_SESSION_ID);
copyStringParam(bundle, params, Engine.KEY_PARAM_UTTERANCE_ID);
copyFloatParam(bundle, params, Engine.KEY_PARAM_VOLUME);
copyFloatParam(bundle, params, Engine.KEY_PARAM_PAN);
// Copy feature strings defined by the framework.
copyStringParam(bundle, params, Engine.KEY_FEATURE_NETWORK_SYNTHESIS);
copyStringParam(bundle, params, Engine.KEY_FEATURE_EMBEDDED_SYNTHESIS);
copyIntParam(bundle, params, Engine.KEY_FEATURE_NETWORK_TIMEOUT_MS);
copyIntParam(bundle, params, Engine.KEY_FEATURE_NETWORK_RETRIES_COUNT);
// Copy over all parameters that start with the name of the
// engine that we are currently connected to. The engine is
// free to interpret them as it chooses.
if (!TextUtils.isEmpty(mCurrentEngine)) {
for (Map.Entry<String, String> entry : params.entrySet()) {
final String key = entry.getKey();
if (key != null && key.startsWith(mCurrentEngine)) {
bundle.putString(key, entry.getValue());
}
}
}
return bundle;
}
return null;
| private void | copyFloatParam(android.os.Bundle bundle, java.util.HashMap params, java.lang.String key)
String valueString = params.get(key);
if (!TextUtils.isEmpty(valueString)) {
try {
float value = Float.parseFloat(valueString);
bundle.putFloat(key, value);
} catch (NumberFormatException ex) {
// don't set the value in the bundle
}
}
| private void | copyIntParam(android.os.Bundle bundle, java.util.HashMap params, java.lang.String key)
String valueString = params.get(key);
if (!TextUtils.isEmpty(valueString)) {
try {
int value = Integer.parseInt(valueString);
bundle.putInt(key, value);
} catch (NumberFormatException ex) {
// don't set the value in the bundle
}
}
| private void | copyStringParam(android.os.Bundle bundle, java.util.HashMap params, java.lang.String key)
String value = params.get(key);
if (value != null) {
bundle.putString(key, value);
}
| private void | dispatchOnInit(int result)
synchronized (mStartLock) {
if (mInitListener != null) {
mInitListener.onInit(result);
mInitListener = null;
}
}
| public java.util.Set | getAvailableLanguages()Query the engine about the set of available languages.
return runAction(new Action<Set<Locale>>() {
@Override
public Set<Locale> run(ITextToSpeechService service) throws RemoteException {
List<Voice> voices = service.getVoices();
if (voices == null) {
return new HashSet<Locale>();
}
HashSet<Locale> locales = new HashSet<Locale>();
for (Voice voice : voices) {
locales.add(voice.getLocale());
}
return locales;
}
}, null, "getAvailableLanguages");
| private android.os.IBinder | getCallerIdentity()
return mServiceConnection.getCallerIdentity();
| public java.lang.String | getCurrentEngine()
return mCurrentEngine;
| public java.lang.String | getDefaultEngine()Gets the package name of the default speech synthesis engine.
return mEnginesHelper.getDefaultEngine();
| public java.util.Locale | getDefaultLanguage()Returns a Locale instance describing the language currently being used as the default
Text-to-speech language.
The locale object returned by this method is NOT a valid one. It has identical form to the
one in {@link #getLanguage()}. Please refer to {@link #getLanguage()} for more information.
return runAction(new Action<Locale>() {
@Override
public Locale run(ITextToSpeechService service) throws RemoteException {
String[] defaultLanguage = service.getClientDefaultLanguage();
return new Locale(defaultLanguage[0], defaultLanguage[1], defaultLanguage[2]);
}
}, null, "getDefaultLanguage");
| public Voice | getDefaultVoice()Returns a Voice instance that's the default voice for the default Text-to-speech language.
return runAction(new Action<Voice>() {
@Override
public Voice run(ITextToSpeechService service) throws RemoteException {
String[] defaultLanguage = service.getClientDefaultLanguage();
if (defaultLanguage == null || defaultLanguage.length == 0) {
Log.e(TAG, "service.getClientDefaultLanguage() returned empty array");
return null;
}
String language = defaultLanguage[0];
String country = (defaultLanguage.length > 1) ? defaultLanguage[1] : "";
String variant = (defaultLanguage.length > 2) ? defaultLanguage[2] : "";
// Sanitize the locale using isLanguageAvailable.
int result = service.isLanguageAvailable(language, country, variant);
if (result >= LANG_AVAILABLE){
if (result < LANG_COUNTRY_VAR_AVAILABLE) {
variant = "";
if (result < LANG_COUNTRY_AVAILABLE) {
country = "";
}
}
} else {
// The default language is not supported.
return null;
}
// Get the default voice name
String voiceName = service.getDefaultVoiceNameFor(language, country, variant);
if (TextUtils.isEmpty(voiceName)) {
return null;
}
// Find it
List<Voice> voices = service.getVoices();
if (voices == null) {
return null;
}
for (Voice voice : voices) {
if (voice.getName().equals(voiceName)) {
return voice;
}
}
return null;
}
}, null, "getDefaultVoice");
| public java.util.List | getEngines()Gets a list of all installed TTS engines.
return mEnginesHelper.getEngines();
| public java.util.Set | getFeatures(java.util.Locale locale)Queries the engine for the set of features it supports for a given locale.
Features can either be framework defined, e.g.
{@link TextToSpeech.Engine#KEY_FEATURE_NETWORK_SYNTHESIS} or engine specific.
Engine specific keys must be prefixed by the name of the engine they
are intended for. These keys can be used as parameters to
{@link TextToSpeech#speak(String, int, java.util.HashMap)} and
{@link TextToSpeech#synthesizeToFile(String, java.util.HashMap, String)}.
Features values are strings and their values must meet restrictions described in their
documentation.
return runAction(new Action<Set<String>>() {
@Override
public Set<String> run(ITextToSpeechService service) throws RemoteException {
String[] features = null;
try {
features = service.getFeaturesForLanguage(
locale.getISO3Language(), locale.getISO3Country(), locale.getVariant());
} catch(MissingResourceException e) {
Log.w(TAG, "Couldn't retrieve 3 letter ISO 639-2/T language and/or ISO 3166 " +
"country code for locale: " + locale, e);
return null;
}
if (features != null) {
final Set<String> featureSet = new HashSet<String>();
Collections.addAll(featureSet, features);
return featureSet;
}
return null;
}
}, null, "getFeatures");
| public java.util.Locale | getLanguage()Returns a Locale instance describing the language currently being used for synthesis
requests sent to the TextToSpeech engine.
In Android 4.2 and before (API <= 17) this function returns the language that is currently
being used by the TTS engine. That is the last language set by this or any other
client by a {@link TextToSpeech#setLanguage} call to the same engine.
In Android versions after 4.2 this function returns the language that is currently being
used for the synthesis requests sent from this client. That is the last language set
by a {@link TextToSpeech#setLanguage} call on this instance.
If a voice is set (by {@link #setVoice(Voice)}), getLanguage will return the language of
the currently set voice.
Please note that the Locale object returned by this method is NOT a valid Locale object. Its
language field contains a three-letter ISO 639-2/T code (where a proper Locale would use
a two-letter ISO 639-1 code), and the country field contains a three-letter ISO 3166 country
code (where a proper Locale would use a two-letter ISO 3166-1 code).
return runAction(new Action<Locale>() {
@Override
public Locale run(ITextToSpeechService service) {
/* No service call, but we're accessing mParams, hence need for
wrapping it as an Action instance */
String lang = mParams.getString(Engine.KEY_PARAM_LANGUAGE, "");
String country = mParams.getString(Engine.KEY_PARAM_COUNTRY, "");
String variant = mParams.getString(Engine.KEY_PARAM_VARIANT, "");
return new Locale(lang, country, variant);
}
}, null, "getLanguage");
| public static int | getMaxSpeechInputLength()Limit of length of input string passed to speak and synthesizeToFile.
return 4000;
| private android.os.Bundle | getParams(android.os.Bundle params)
if (params != null && !params.isEmpty()) {
Bundle bundle = new Bundle(mParams);
bundle.putAll(params);
verifyIntegerBundleParam(bundle, Engine.KEY_PARAM_STREAM);
verifyIntegerBundleParam(bundle, Engine.KEY_PARAM_SESSION_ID);
verifyStringBundleParam(bundle, Engine.KEY_PARAM_UTTERANCE_ID);
verifyFloatBundleParam(bundle, Engine.KEY_PARAM_VOLUME);
verifyFloatBundleParam(bundle, Engine.KEY_PARAM_PAN);
// Copy feature strings defined by the framework.
verifyBooleanBundleParam(bundle, Engine.KEY_FEATURE_NETWORK_SYNTHESIS);
verifyBooleanBundleParam(bundle, Engine.KEY_FEATURE_EMBEDDED_SYNTHESIS);
verifyIntegerBundleParam(bundle, Engine.KEY_FEATURE_NETWORK_TIMEOUT_MS);
verifyIntegerBundleParam(bundle, Engine.KEY_FEATURE_NETWORK_RETRIES_COUNT);
return bundle;
} else {
return mParams;
}
| public Voice | getVoice()Returns a Voice instance describing the voice currently being used for synthesis
requests sent to the TextToSpeech engine.
return runAction(new Action<Voice>() {
@Override
public Voice run(ITextToSpeechService service) throws RemoteException {
String voiceName = mParams.getString(Engine.KEY_PARAM_VOICE_NAME, "");
if (TextUtils.isEmpty(voiceName)) {
return null;
}
List<Voice> voices = service.getVoices();
if (voices == null) {
return null;
}
for (Voice voice : voices) {
if (voice.getName().equals(voiceName)) {
return voice;
}
}
return null;
}
}, null, "getVoice");
| public java.util.Set | getVoices()Query the engine about the set of available voices.
Each TTS Engine can expose multiple voices for each locale, each with a different set of
features.
return runAction(new Action<Set<Voice>>() {
@Override
public Set<Voice> run(ITextToSpeechService service) throws RemoteException {
List<Voice> voices = service.getVoices();
return (voices != null) ? new HashSet<Voice>(voices) : new HashSet<Voice>();
}
}, null, "getVoices");
| private int | initTts()
// Step 1: Try connecting to the engine that was requested.
if (mRequestedEngine != null) {
if (mEnginesHelper.isEngineInstalled(mRequestedEngine)) {
if (connectToEngine(mRequestedEngine)) {
mCurrentEngine = mRequestedEngine;
return SUCCESS;
} else if (!mUseFallback) {
mCurrentEngine = null;
dispatchOnInit(ERROR);
return ERROR;
}
} else if (!mUseFallback) {
Log.i(TAG, "Requested engine not installed: " + mRequestedEngine);
mCurrentEngine = null;
dispatchOnInit(ERROR);
return ERROR;
}
}
// Step 2: Try connecting to the user's default engine.
final String defaultEngine = getDefaultEngine();
if (defaultEngine != null && !defaultEngine.equals(mRequestedEngine)) {
if (connectToEngine(defaultEngine)) {
mCurrentEngine = defaultEngine;
return SUCCESS;
}
}
// Step 3: Try connecting to the highest ranked engine in the
// system.
final String highestRanked = mEnginesHelper.getHighestRankedEngineName();
if (highestRanked != null && !highestRanked.equals(mRequestedEngine) &&
!highestRanked.equals(defaultEngine)) {
if (connectToEngine(highestRanked)) {
mCurrentEngine = highestRanked;
return SUCCESS;
}
}
// NOTE: The API currently does not allow the caller to query whether
// they are actually connected to any engine. This might fail for various
// reasons like if the user disables all her TTS engines.
mCurrentEngine = null;
dispatchOnInit(ERROR);
return ERROR;
| public int | isLanguageAvailable(java.util.Locale loc)Checks if the specified language as represented by the Locale is available and supported.
return runAction(new Action<Integer>() {
@Override
public Integer run(ITextToSpeechService service) throws RemoteException {
String language = null, country = null;
try {
language = loc.getISO3Language();
} catch (MissingResourceException e) {
Log.w(TAG, "Couldn't retrieve ISO 639-2/T language code for locale: " + loc, e);
return LANG_NOT_SUPPORTED;
}
try {
country = loc.getISO3Country();
} catch (MissingResourceException e) {
Log.w(TAG, "Couldn't retrieve ISO 3166 country code for locale: " + loc, e);
return LANG_NOT_SUPPORTED;
}
return service.isLanguageAvailable(language, country, loc.getVariant());
}
}, LANG_NOT_SUPPORTED, "isLanguageAvailable");
| public boolean | isSpeaking()Checks whether the TTS engine is busy speaking. Note that a speech item is
considered complete once it's audio data has been sent to the audio mixer, or
written to a file. There might be a finite lag between this point, and when
the audio hardware completes playback.
return runAction(new Action<Boolean>() {
@Override
public Boolean run(ITextToSpeechService service) throws RemoteException {
return service.isSpeaking();
}
}, false, "isSpeaking");
| private android.net.Uri | makeResourceUri(java.lang.String packageName, int resourceId)
return new Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.encodedAuthority(packageName)
.appendEncodedPath(String.valueOf(resourceId))
.build();
| public int | playEarcon(java.lang.String earcon, int queueMode, android.os.Bundle params, java.lang.String utteranceId)Plays the earcon using the specified queueing mode and parameters.
The earcon must already have been added with {@link #addEarcon(String, String)} or
{@link #addEarcon(String, String, int)}.
This method is asynchronous, i.e. the method just adds the request to the queue of TTS
requests and then returns. The synthesis might not have finished (or even started!) at the
time when this method returns. In order to reliably detect errors during synthesis,
we recommend setting an utterance progress listener (see
{@link #setOnUtteranceProgressListener}) and using the
{@link Engine#KEY_PARAM_UTTERANCE_ID} parameter.
return runAction(new Action<Integer>() {
@Override
public Integer run(ITextToSpeechService service) throws RemoteException {
Uri earconUri = mEarcons.get(earcon);
if (earconUri == null) {
return ERROR;
}
return service.playAudio(getCallerIdentity(), earconUri, queueMode,
getParams(params), utteranceId);
}
}, ERROR, "playEarcon");
| public int | playEarcon(java.lang.String earcon, int queueMode, java.util.HashMap params)Plays the earcon using the specified queueing mode and parameters.
The earcon must already have been added with {@link #addEarcon(String, String)} or
{@link #addEarcon(String, String, int)}.
This method is asynchronous, i.e. the method just adds the request to the queue of TTS
requests and then returns. The synthesis might not have finished (or even started!) at the
time when this method returns. In order to reliably detect errors during synthesis,
we recommend setting an utterance progress listener (see
{@link #setOnUtteranceProgressListener}) and using the
{@link Engine#KEY_PARAM_UTTERANCE_ID} parameter.
return playEarcon(earcon, queueMode, convertParamsHashMaptoBundle(params),
params == null ? null : params.get(Engine.KEY_PARAM_UTTERANCE_ID));
| public int | playSilence(long durationInMs, int queueMode, java.util.HashMap params)Plays silence for the specified amount of time using the specified
queue mode.
This method is asynchronous, i.e. the method just adds the request to the queue of TTS
requests and then returns. The synthesis might not have finished (or even started!) at the
time when this method returns. In order to reliably detect errors during synthesis,
we recommend setting an utterance progress listener (see
{@link #setOnUtteranceProgressListener}) and using the
{@link Engine#KEY_PARAM_UTTERANCE_ID} parameter.
return playSilentUtterance(durationInMs, queueMode,
params == null ? null : params.get(Engine.KEY_PARAM_UTTERANCE_ID));
| public int | playSilentUtterance(long durationInMs, int queueMode, java.lang.String utteranceId)Plays silence for the specified amount of time using the specified
queue mode.
This method is asynchronous, i.e. the method just adds the request to the queue of TTS
requests and then returns. The synthesis might not have finished (or even started!) at the
time when this method returns. In order to reliably detect errors during synthesis,
we recommend setting an utterance progress listener (see
{@link #setOnUtteranceProgressListener}) and using the
{@link Engine#KEY_PARAM_UTTERANCE_ID} parameter.
return runAction(new Action<Integer>() {
@Override
public Integer run(ITextToSpeechService service) throws RemoteException {
return service.playSilence(getCallerIdentity(), durationInMs,
queueMode, utteranceId);
}
}, ERROR, "playSilentUtterance");
| private R | runAction(android.speech.tts.TextToSpeech$Action action, R errorResult, java.lang.String method)
return runAction(action, errorResult, method, true, true);
| private R | runAction(android.speech.tts.TextToSpeech$Action action, R errorResult, java.lang.String method, boolean reconnect, boolean onlyEstablishedConnection)
synchronized (mStartLock) {
if (mServiceConnection == null) {
Log.w(TAG, method + " failed: not bound to TTS engine");
return errorResult;
}
return mServiceConnection.runAction(action, errorResult, method, reconnect,
onlyEstablishedConnection);
}
| private R | runActionNoReconnect(android.speech.tts.TextToSpeech$Action action, R errorResult, java.lang.String method, boolean onlyEstablishedConnection)
return runAction(action, errorResult, method, false, onlyEstablishedConnection);
| public int | setAudioAttributes(android.media.AudioAttributes audioAttributes)Sets the audio attributes to be used when speaking text or playing
back a file.
if (audioAttributes != null) {
synchronized (mStartLock) {
mParams.putParcelable(Engine.KEY_PARAM_AUDIO_ATTRIBUTES,
audioAttributes);
}
return SUCCESS;
}
return ERROR;
| public int | setEngineByPackageName(java.lang.String enginePackageName)Sets the TTS engine to use.
mRequestedEngine = enginePackageName;
return initTts();
| public int | setLanguage(java.util.Locale loc)Sets the text-to-speech language.
The TTS engine will try to use the closest match to the specified
language as represented by the Locale, but there is no guarantee that the exact same Locale
will be used. Use {@link #isLanguageAvailable(Locale)} to check the level of support
before choosing the language to use for the next utterances.
This method sets the current voice to the default one for the given Locale;
{@link #getVoice()} can be used to retrieve it.
return runAction(new Action<Integer>() {
@Override
public Integer run(ITextToSpeechService service) throws RemoteException {
if (loc == null) {
return LANG_NOT_SUPPORTED;
}
String language = null, country = null;
try {
language = loc.getISO3Language();
} catch (MissingResourceException e) {
Log.w(TAG, "Couldn't retrieve ISO 639-2/T language code for locale: " + loc, e);
return LANG_NOT_SUPPORTED;
}
try {
country = loc.getISO3Country();
} catch (MissingResourceException e) {
Log.w(TAG, "Couldn't retrieve ISO 3166 country code for locale: " + loc, e);
return LANG_NOT_SUPPORTED;
}
String variant = loc.getVariant();
// As of API level 21, setLanguage is implemented using setVoice.
// (which, in the default implementation, will call loadLanguage on the service
// interface).
// Sanitize locale using isLanguageAvailable.
int result = service.isLanguageAvailable( language, country, variant);
if (result >= LANG_AVAILABLE){
if (result < LANG_COUNTRY_VAR_AVAILABLE) {
variant = "";
if (result < LANG_COUNTRY_AVAILABLE) {
country = "";
}
}
// Get the default voice for the locale.
String voiceName = service.getDefaultVoiceNameFor(language, country, variant);
if (TextUtils.isEmpty(voiceName)) {
Log.w(TAG, "Couldn't find the default voice for " + language + "/" +
country + "/" + variant);
return LANG_NOT_SUPPORTED;
}
// Load it.
if (service.loadVoice(getCallerIdentity(), voiceName) == TextToSpeech.ERROR) {
return LANG_NOT_SUPPORTED;
}
mParams.putString(Engine.KEY_PARAM_VOICE_NAME, voiceName);
mParams.putString(Engine.KEY_PARAM_LANGUAGE, language);
mParams.putString(Engine.KEY_PARAM_COUNTRY, country);
mParams.putString(Engine.KEY_PARAM_VARIANT, variant);
}
return result;
}
}, LANG_NOT_SUPPORTED, "setLanguage");
| public int | setOnUtteranceCompletedListener(android.speech.tts.TextToSpeech$OnUtteranceCompletedListener listener)Sets the listener that will be notified when synthesis of an utterance completes.
mUtteranceProgressListener = UtteranceProgressListener.from(listener);
return TextToSpeech.SUCCESS;
| public int | setOnUtteranceProgressListener(UtteranceProgressListener listener)Sets the listener that will be notified of various events related to the
synthesis of a given utterance.
See {@link UtteranceProgressListener} and
{@link TextToSpeech.Engine#KEY_PARAM_UTTERANCE_ID}.
mUtteranceProgressListener = listener;
return TextToSpeech.SUCCESS;
| public int | setPitch(float pitch)Sets the speech pitch for the TextToSpeech engine.
This has no effect on any pre-recorded speech.
if (pitch > 0.0f) {
int intPitch = (int)(pitch * 100);
if (intPitch > 0) {
synchronized (mStartLock) {
mParams.putInt(Engine.KEY_PARAM_PITCH, intPitch);
}
return SUCCESS;
}
}
return ERROR;
| public int | setSpeechRate(float speechRate)Sets the speech rate.
This has no effect on any pre-recorded speech.
if (speechRate > 0.0f) {
int intRate = (int)(speechRate * 100);
if (intRate > 0) {
synchronized (mStartLock) {
mParams.putInt(Engine.KEY_PARAM_RATE, intRate);
}
return SUCCESS;
}
}
return ERROR;
| public int | setVoice(Voice voice)Sets the text-to-speech voice.
return runAction(new Action<Integer>() {
@Override
public Integer run(ITextToSpeechService service) throws RemoteException {
int result = service.loadVoice(getCallerIdentity(), voice.getName());
if (result == SUCCESS) {
mParams.putString(Engine.KEY_PARAM_VOICE_NAME, voice.getName());
// Set the language/country/variant, so #getLanguage will return the voice
// locale when called.
String language = "";
try {
language = voice.getLocale().getISO3Language();
} catch (MissingResourceException e) {
Log.w(TAG, "Couldn't retrieve ISO 639-2/T language code for locale: " +
voice.getLocale(), e);
}
String country = "";
try {
country = voice.getLocale().getISO3Country();
} catch (MissingResourceException e) {
Log.w(TAG, "Couldn't retrieve ISO 3166 country code for locale: " +
voice.getLocale(), e);
}
mParams.putString(Engine.KEY_PARAM_LANGUAGE, language);
mParams.putString(Engine.KEY_PARAM_COUNTRY, country);
mParams.putString(Engine.KEY_PARAM_VARIANT, voice.getLocale().getVariant());
}
return result;
}
}, LANG_NOT_SUPPORTED, "setVoice");
| public void | shutdown()Releases the resources used by the TextToSpeech engine.
It is good practice for instance to call this method in the onDestroy() method of an Activity
so the TextToSpeech engine can be cleanly stopped.
// Special case, we are asked to shutdown connection that did finalize its connection.
synchronized (mStartLock) {
if (mConnectingServiceConnection != null) {
mContext.unbindService(mConnectingServiceConnection);
mConnectingServiceConnection = null;
return;
}
}
// Post connection case
runActionNoReconnect(new Action<Void>() {
@Override
public Void run(ITextToSpeechService service) throws RemoteException {
service.setCallback(getCallerIdentity(), null);
service.stop(getCallerIdentity());
mServiceConnection.disconnect();
// Context#unbindService does not result in a call to
// ServiceConnection#onServiceDisconnected. As a result, the
// service ends up being destroyed (if there are no other open
// connections to it) but the process lives on and the
// ServiceConnection continues to refer to the destroyed service.
//
// This leads to tons of log spam about SynthThread being dead.
mServiceConnection = null;
mCurrentEngine = null;
return null;
}
}, null, "shutdown", false);
| public int | speak(java.lang.CharSequence text, int queueMode, android.os.Bundle params, java.lang.String utteranceId)Speaks the text using the specified queuing strategy and speech parameters, the text may
be spanned with TtsSpans.
This method is asynchronous, i.e. the method just adds the request to the queue of TTS
requests and then returns. The synthesis might not have finished (or even started!) at the
time when this method returns. In order to reliably detect errors during synthesis,
we recommend setting an utterance progress listener (see
{@link #setOnUtteranceProgressListener}) and using the
{@link Engine#KEY_PARAM_UTTERANCE_ID} parameter.
return runAction(new Action<Integer>() {
@Override
public Integer run(ITextToSpeechService service) throws RemoteException {
Uri utteranceUri = mUtterances.get(text);
if (utteranceUri != null) {
return service.playAudio(getCallerIdentity(), utteranceUri, queueMode,
getParams(params), utteranceId);
} else {
return service.speak(getCallerIdentity(), text, queueMode, getParams(params),
utteranceId);
}
}
}, ERROR, "speak");
| public int | speak(java.lang.String text, int queueMode, java.util.HashMap params)Speaks the string using the specified queuing strategy and speech parameters.
This method is asynchronous, i.e. the method just adds the request to the queue of TTS
requests and then returns. The synthesis might not have finished (or even started!) at the
time when this method returns. In order to reliably detect errors during synthesis,
we recommend setting an utterance progress listener (see
{@link #setOnUtteranceProgressListener}) and using the
{@link Engine#KEY_PARAM_UTTERANCE_ID} parameter.
return speak(text, queueMode, convertParamsHashMaptoBundle(params),
params == null ? null : params.get(Engine.KEY_PARAM_UTTERANCE_ID));
| public int | stop()Interrupts the current utterance (whether played or rendered to file) and discards other
utterances in the queue.
return runAction(new Action<Integer>() {
@Override
public Integer run(ITextToSpeechService service) throws RemoteException {
return service.stop(getCallerIdentity());
}
}, ERROR, "stop");
| public int | synthesizeToFile(java.lang.CharSequence text, android.os.Bundle params, java.io.File file, java.lang.String utteranceId)Synthesizes the given text to a file using the specified parameters.
This method is asynchronous, i.e. the method just adds the request to the queue of TTS
requests and then returns. The synthesis might not have finished (or even started!) at the
time when this method returns. In order to reliably detect errors during synthesis,
we recommend setting an utterance progress listener (see
{@link #setOnUtteranceProgressListener}).
return runAction(new Action<Integer>() {
@Override
public Integer run(ITextToSpeechService service) throws RemoteException {
ParcelFileDescriptor fileDescriptor;
int returnValue;
try {
if(file.exists() && !file.canWrite()) {
Log.e(TAG, "Can't write to " + file);
return ERROR;
}
fileDescriptor = ParcelFileDescriptor.open(file,
ParcelFileDescriptor.MODE_WRITE_ONLY |
ParcelFileDescriptor.MODE_CREATE |
ParcelFileDescriptor.MODE_TRUNCATE);
returnValue = service.synthesizeToFileDescriptor(getCallerIdentity(), text,
fileDescriptor, getParams(params), utteranceId);
fileDescriptor.close();
return returnValue;
} catch (FileNotFoundException e) {
Log.e(TAG, "Opening file " + file + " failed", e);
return ERROR;
} catch (IOException e) {
Log.e(TAG, "Closing file " + file + " failed", e);
return ERROR;
}
}
}, ERROR, "synthesizeToFile");
| public int | synthesizeToFile(java.lang.String text, java.util.HashMap params, java.lang.String filename)Synthesizes the given text to a file using the specified parameters.
This method is asynchronous, i.e. the method just adds the request to the queue of TTS
requests and then returns. The synthesis might not have finished (or even started!) at the
time when this method returns. In order to reliably detect errors during synthesis,
we recommend setting an utterance progress listener (see
{@link #setOnUtteranceProgressListener}) and using the
{@link Engine#KEY_PARAM_UTTERANCE_ID} parameter.
return synthesizeToFile(text, convertParamsHashMaptoBundle(params),
new File(filename), params.get(Engine.KEY_PARAM_UTTERANCE_ID));
| private static boolean | verifyBooleanBundleParam(android.os.Bundle bundle, java.lang.String key)
if (bundle.containsKey(key)) {
if (!(bundle.get(key) instanceof Boolean ||
bundle.get(key) instanceof String)) {
bundle.remove(key);
Log.w(TAG, "Synthesis request paramter " + key + " containst value "
+ " with invalid type. Should be a Boolean or String");
return false;
}
}
return true;
| private static boolean | verifyFloatBundleParam(android.os.Bundle bundle, java.lang.String key)
if (bundle.containsKey(key)) {
if (!(bundle.get(key) instanceof Float ||
bundle.get(key) instanceof Double)) {
bundle.remove(key);
Log.w(TAG, "Synthesis request paramter " + key + " containst value "
+ " with invalid type. Should be a Float or a Double");
return false;
}
}
return true;
| private static boolean | verifyIntegerBundleParam(android.os.Bundle bundle, java.lang.String key)
if (bundle.containsKey(key)) {
if (!(bundle.get(key) instanceof Integer ||
bundle.get(key) instanceof Long)) {
bundle.remove(key);
Log.w(TAG, "Synthesis request paramter " + key + " containst value "
+ " with invalid type. Should be an Integer or a Long");
return false;
}
}
return true;
| private static boolean | verifyStringBundleParam(android.os.Bundle bundle, java.lang.String key)
if (bundle.containsKey(key)) {
if (!(bundle.get(key) instanceof String)) {
bundle.remove(key);
Log.w(TAG, "Synthesis request paramter " + key + " containst value "
+ " with invalid type. Should be a String");
return false;
}
}
return true;
|
|