TextToSpeech.java revision 672695e42387a024083d198f3d665f354ef1d27c
1/* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16package android.speech.tts; 17 18import android.annotation.SdkConstant; 19import android.annotation.SdkConstant.SdkConstantType; 20import android.content.ComponentName; 21import android.content.ContentResolver; 22import android.content.Context; 23import android.content.Intent; 24import android.content.ServiceConnection; 25import android.media.AudioAttributes; 26import android.media.AudioManager; 27import android.net.Uri; 28import android.os.AsyncTask; 29import android.os.Bundle; 30import android.os.IBinder; 31import android.os.ParcelFileDescriptor; 32import android.os.RemoteException; 33import android.provider.Settings; 34import android.text.TextUtils; 35import android.util.Log; 36 37import java.io.File; 38import java.io.FileNotFoundException; 39import java.io.IOException; 40import java.util.ArrayList; 41import java.util.Collections; 42import java.util.HashMap; 43import java.util.HashSet; 44import java.util.List; 45import java.util.Locale; 46import java.util.Map; 47import java.util.MissingResourceException; 48import java.util.Set; 49import java.util.TreeSet; 50 51/** 52 * 53 * Synthesizes speech from text for immediate playback or to create a sound file. 54 * <p>A TextToSpeech instance can only be used to synthesize text once it has completed its 55 * initialization. Implement the {@link TextToSpeech.OnInitListener} to be 56 * notified of the completion of the initialization.<br> 57 * When you are done using the TextToSpeech instance, call the {@link #shutdown()} method 58 * to release the native resources used by the TextToSpeech engine. 59 */ 60public class TextToSpeech { 61 62 private static final String TAG = "TextToSpeech"; 63 64 /** 65 * Denotes a successful operation. 66 */ 67 public static final int SUCCESS = 0; 68 /** 69 * Denotes a generic operation failure. 70 */ 71 public static final int ERROR = -1; 72 73 /** 74 * Denotes a stop requested by a client. It's used only on the service side of the API, 75 * client should never expect to see this result code. 76 */ 77 public static final int STOPPED = -2; 78 79 /** 80 * Denotes a failure of a TTS engine to synthesize the given input. 81 */ 82 public static final int ERROR_SYNTHESIS = -3; 83 84 /** 85 * Denotes a failure of a TTS service. 86 */ 87 public static final int ERROR_SERVICE = -4; 88 89 /** 90 * Denotes a failure related to the output (audio device or a file). 91 */ 92 public static final int ERROR_OUTPUT = -5; 93 94 /** 95 * Denotes a failure caused by a network connectivity problems. 96 */ 97 public static final int ERROR_NETWORK = -6; 98 99 /** 100 * Denotes a failure caused by network timeout. 101 */ 102 public static final int ERROR_NETWORK_TIMEOUT = -7; 103 104 /** 105 * Denotes a failure caused by an invalid request. 106 */ 107 public static final int ERROR_INVALID_REQUEST = -8; 108 109 /** 110 * Denotes a failure caused by an unfinished download of the voice data. 111 * @see Engine#KEY_FEATURE_NOT_INSTALLED 112 */ 113 public static final int ERROR_NOT_INSTALLED_YET = -9; 114 115 /** 116 * Queue mode where all entries in the playback queue (media to be played 117 * and text to be synthesized) are dropped and replaced by the new entry. 118 * Queues are flushed with respect to a given calling app. Entries in the queue 119 * from other callees are not discarded. 120 */ 121 public static final int QUEUE_FLUSH = 0; 122 /** 123 * Queue mode where the new entry is added at the end of the playback queue. 124 */ 125 public static final int QUEUE_ADD = 1; 126 /** 127 * Queue mode where the entire playback queue is purged. This is different 128 * from {@link #QUEUE_FLUSH} in that all entries are purged, not just entries 129 * from a given caller. 130 * 131 * @hide 132 */ 133 static final int QUEUE_DESTROY = 2; 134 135 /** 136 * Denotes the language is available exactly as specified by the locale. 137 */ 138 public static final int LANG_COUNTRY_VAR_AVAILABLE = 2; 139 140 /** 141 * Denotes the language is available for the language and country specified 142 * by the locale, but not the variant. 143 */ 144 public static final int LANG_COUNTRY_AVAILABLE = 1; 145 146 /** 147 * Denotes the language is available for the language by the locale, 148 * but not the country and variant. 149 */ 150 public static final int LANG_AVAILABLE = 0; 151 152 /** 153 * Denotes the language data is missing. 154 */ 155 public static final int LANG_MISSING_DATA = -1; 156 157 /** 158 * Denotes the language is not supported. 159 */ 160 public static final int LANG_NOT_SUPPORTED = -2; 161 162 /** 163 * Broadcast Action: The TextToSpeech synthesizer has completed processing 164 * of all the text in the speech queue. 165 * 166 * Note that this notifies callers when the <b>engine</b> has finished has 167 * processing text data. Audio playback might not have completed (or even started) 168 * at this point. If you wish to be notified when this happens, see 169 * {@link OnUtteranceCompletedListener}. 170 */ 171 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 172 public static final String ACTION_TTS_QUEUE_PROCESSING_COMPLETED = 173 "android.speech.tts.TTS_QUEUE_PROCESSING_COMPLETED"; 174 175 /** 176 * Interface definition of a callback to be invoked indicating the completion of the 177 * TextToSpeech engine initialization. 178 */ 179 public interface OnInitListener { 180 /** 181 * Called to signal the completion of the TextToSpeech engine initialization. 182 * 183 * @param status {@link TextToSpeech#SUCCESS} or {@link TextToSpeech#ERROR}. 184 */ 185 public void onInit(int status); 186 } 187 188 /** 189 * Listener that will be called when the TTS service has 190 * completed synthesizing an utterance. This is only called if the utterance 191 * has an utterance ID (see {@link TextToSpeech.Engine#KEY_PARAM_UTTERANCE_ID}). 192 * 193 * @deprecated Use {@link UtteranceProgressListener} instead. 194 */ 195 @Deprecated 196 public interface OnUtteranceCompletedListener { 197 /** 198 * Called when an utterance has been synthesized. 199 * 200 * @param utteranceId the identifier of the utterance. 201 */ 202 public void onUtteranceCompleted(String utteranceId); 203 } 204 205 /** 206 * Constants and parameter names for controlling text-to-speech. These include: 207 * 208 * <ul> 209 * <li> 210 * Intents to ask engine to install data or check its data and 211 * extras for a TTS engine's check data activity. 212 * </li> 213 * <li> 214 * Keys for the parameters passed with speak commands, e.g. 215 * {@link Engine#KEY_PARAM_UTTERANCE_ID}, {@link Engine#KEY_PARAM_STREAM}. 216 * </li> 217 * <li> 218 * A list of feature strings that engines might support, e.g 219 * {@link Engine#KEY_FEATURE_NETWORK_SYNTHESIS}). These values may be passed in to 220 * {@link TextToSpeech#speak} and {@link TextToSpeech#synthesizeToFile} to modify 221 * engine behaviour. The engine can be queried for the set of features it supports 222 * through {@link TextToSpeech#getFeatures(java.util.Locale)}. 223 * </li> 224 * </ul> 225 */ 226 public class Engine { 227 228 /** 229 * Default speech rate. 230 * @hide 231 */ 232 public static final int DEFAULT_RATE = 100; 233 234 /** 235 * Default pitch. 236 * @hide 237 */ 238 public static final int DEFAULT_PITCH = 100; 239 240 /** 241 * Default volume. 242 * @hide 243 */ 244 public static final float DEFAULT_VOLUME = 1.0f; 245 246 /** 247 * Default pan (centered). 248 * @hide 249 */ 250 public static final float DEFAULT_PAN = 0.0f; 251 252 /** 253 * Default value for {@link Settings.Secure#TTS_USE_DEFAULTS}. 254 * @hide 255 */ 256 public static final int USE_DEFAULTS = 0; // false 257 258 /** 259 * Package name of the default TTS engine. 260 * 261 * @hide 262 * @deprecated No longer in use, the default engine is determined by 263 * the sort order defined in {@link TtsEngines}. Note that 264 * this doesn't "break" anything because there is no guarantee that 265 * the engine specified below is installed on a given build, let 266 * alone be the default. 267 */ 268 @Deprecated 269 public static final String DEFAULT_ENGINE = "com.svox.pico"; 270 271 /** 272 * Default audio stream used when playing synthesized speech. 273 */ 274 public static final int DEFAULT_STREAM = AudioManager.STREAM_MUSIC; 275 276 /** 277 * Indicates success when checking the installation status of the resources used by the 278 * TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent. 279 */ 280 public static final int CHECK_VOICE_DATA_PASS = 1; 281 282 /** 283 * Indicates failure when checking the installation status of the resources used by the 284 * TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent. 285 */ 286 public static final int CHECK_VOICE_DATA_FAIL = 0; 287 288 /** 289 * Indicates erroneous data when checking the installation status of the resources used by 290 * the TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent. 291 * 292 * @deprecated Use CHECK_VOICE_DATA_FAIL instead. 293 */ 294 @Deprecated 295 public static final int CHECK_VOICE_DATA_BAD_DATA = -1; 296 297 /** 298 * Indicates missing resources when checking the installation status of the resources used 299 * by the TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent. 300 * 301 * @deprecated Use CHECK_VOICE_DATA_FAIL instead. 302 */ 303 @Deprecated 304 public static final int CHECK_VOICE_DATA_MISSING_DATA = -2; 305 306 /** 307 * Indicates missing storage volume when checking the installation status of the resources 308 * used by the TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent. 309 * 310 * @deprecated Use CHECK_VOICE_DATA_FAIL instead. 311 */ 312 @Deprecated 313 public static final int CHECK_VOICE_DATA_MISSING_VOLUME = -3; 314 315 /** 316 * Intent for starting a TTS service. Services that handle this intent must 317 * extend {@link TextToSpeechService}. Normal applications should not use this intent 318 * directly, instead they should talk to the TTS service using the the methods in this 319 * class. 320 */ 321 @SdkConstant(SdkConstantType.SERVICE_ACTION) 322 public static final String INTENT_ACTION_TTS_SERVICE = 323 "android.intent.action.TTS_SERVICE"; 324 325 /** 326 * Name under which a text to speech engine publishes information about itself. 327 * This meta-data should reference an XML resource containing a 328 * <code><{@link android.R.styleable#TextToSpeechEngine tts-engine}></code> 329 * tag. 330 */ 331 public static final String SERVICE_META_DATA = "android.speech.tts"; 332 333 // intents to ask engine to install data or check its data 334 /** 335 * Activity Action: Triggers the platform TextToSpeech engine to 336 * start the activity that installs the resource files on the device 337 * that are required for TTS to be operational. Since the installation 338 * of the data can be interrupted or declined by the user, the application 339 * shouldn't expect successful installation upon return from that intent, 340 * and if need be, should check installation status with 341 * {@link #ACTION_CHECK_TTS_DATA}. 342 */ 343 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 344 public static final String ACTION_INSTALL_TTS_DATA = 345 "android.speech.tts.engine.INSTALL_TTS_DATA"; 346 347 /** 348 * Broadcast Action: broadcast to signal the change in the list of available 349 * languages or/and their features. 350 */ 351 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 352 public static final String ACTION_TTS_DATA_INSTALLED = 353 "android.speech.tts.engine.TTS_DATA_INSTALLED"; 354 355 /** 356 * Activity Action: Starts the activity from the platform TextToSpeech 357 * engine to verify the proper installation and availability of the 358 * resource files on the system. Upon completion, the activity will 359 * return one of the following codes: 360 * {@link #CHECK_VOICE_DATA_PASS}, 361 * {@link #CHECK_VOICE_DATA_FAIL}, 362 * <p> Moreover, the data received in the activity result will contain the following 363 * fields: 364 * <ul> 365 * <li>{@link #EXTRA_AVAILABLE_VOICES} which contains an ArrayList<String> of all the 366 * available voices. The format of each voice is: lang-COUNTRY-variant where COUNTRY and 367 * variant are optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE").</li> 368 * <li>{@link #EXTRA_UNAVAILABLE_VOICES} which contains an ArrayList<String> of all the 369 * unavailable voices (ones that user can install). The format of each voice is: 370 * lang-COUNTRY-variant where COUNTRY and variant are optional (ie, "eng" or 371 * "eng-USA" or "eng-USA-FEMALE").</li> 372 * </ul> 373 */ 374 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 375 public static final String ACTION_CHECK_TTS_DATA = 376 "android.speech.tts.engine.CHECK_TTS_DATA"; 377 378 /** 379 * Activity intent for getting some sample text to use for demonstrating TTS. Specific 380 * locale have to be requested by passing following extra parameters: 381 * <ul> 382 * <li>language</li> 383 * <li>country</li> 384 * <li>variant</li> 385 * </ul> 386 * 387 * Upon completion, the activity result may contain the following fields: 388 * <ul> 389 * <li>{@link #EXTRA_SAMPLE_TEXT} which contains an String with sample text.</li> 390 * </ul> 391 */ 392 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 393 public static final String ACTION_GET_SAMPLE_TEXT = 394 "android.speech.tts.engine.GET_SAMPLE_TEXT"; 395 396 /** 397 * Extra information received with the {@link #ACTION_GET_SAMPLE_TEXT} intent result where 398 * the TextToSpeech engine returns an String with sample text for requested voice 399 */ 400 public static final String EXTRA_SAMPLE_TEXT = "sampleText"; 401 402 403 // extras for a TTS engine's check data activity 404 /** 405 * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent result where 406 * the TextToSpeech engine returns an ArrayList<String> of all the available voices. 407 * The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are 408 * optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). 409 */ 410 public static final String EXTRA_AVAILABLE_VOICES = "availableVoices"; 411 412 /** 413 * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent result where 414 * the TextToSpeech engine returns an ArrayList<String> of all the unavailable voices. 415 * The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are 416 * optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). 417 */ 418 public static final String EXTRA_UNAVAILABLE_VOICES = "unavailableVoices"; 419 420 /** 421 * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent result where 422 * the TextToSpeech engine specifies the path to its resources. 423 * 424 * It may be used by language packages to find out where to put their data. 425 * 426 * @deprecated TTS engine implementation detail, this information has no use for 427 * text-to-speech API client. 428 */ 429 @Deprecated 430 public static final String EXTRA_VOICE_DATA_ROOT_DIRECTORY = "dataRoot"; 431 432 /** 433 * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent result where 434 * the TextToSpeech engine specifies the file names of its resources under the 435 * resource path. 436 * 437 * @deprecated TTS engine implementation detail, this information has no use for 438 * text-to-speech API client. 439 */ 440 @Deprecated 441 public static final String EXTRA_VOICE_DATA_FILES = "dataFiles"; 442 443 /** 444 * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent result where 445 * the TextToSpeech engine specifies the locale associated with each resource file. 446 * 447 * @deprecated TTS engine implementation detail, this information has no use for 448 * text-to-speech API client. 449 */ 450 @Deprecated 451 public static final String EXTRA_VOICE_DATA_FILES_INFO = "dataFilesInfo"; 452 453 /** 454 * Extra information sent with the {@link #ACTION_CHECK_TTS_DATA} intent where the 455 * caller indicates to the TextToSpeech engine which specific sets of voice data to 456 * check for by sending an ArrayList<String> of the voices that are of interest. 457 * The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are 458 * optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). 459 * 460 * @deprecated Redundant functionality, checking for existence of specific sets of voice 461 * data can be done on client side. 462 */ 463 @Deprecated 464 public static final String EXTRA_CHECK_VOICE_DATA_FOR = "checkVoiceDataFor"; 465 466 // extras for a TTS engine's data installation 467 /** 468 * Extra information received with the {@link #ACTION_TTS_DATA_INSTALLED} intent result. 469 * It indicates whether the data files for the synthesis engine were successfully 470 * installed. The installation was initiated with the {@link #ACTION_INSTALL_TTS_DATA} 471 * intent. The possible values for this extra are 472 * {@link TextToSpeech#SUCCESS} and {@link TextToSpeech#ERROR}. 473 * 474 * @deprecated No longer in use. If client ise interested in information about what 475 * changed, is should send ACTION_CHECK_TTS_DATA intent to discover available voices. 476 */ 477 @Deprecated 478 public static final String EXTRA_TTS_DATA_INSTALLED = "dataInstalled"; 479 480 // keys for the parameters passed with speak commands. Hidden keys are used internally 481 // to maintain engine state for each TextToSpeech instance. 482 /** 483 * @hide 484 */ 485 public static final String KEY_PARAM_RATE = "rate"; 486 487 /** 488 * @hide 489 */ 490 public static final String KEY_PARAM_VOICE_NAME = "voiceName"; 491 492 /** 493 * @hide 494 */ 495 public static final String KEY_PARAM_LANGUAGE = "language"; 496 497 /** 498 * @hide 499 */ 500 public static final String KEY_PARAM_COUNTRY = "country"; 501 502 /** 503 * @hide 504 */ 505 public static final String KEY_PARAM_VARIANT = "variant"; 506 507 /** 508 * @hide 509 */ 510 public static final String KEY_PARAM_ENGINE = "engine"; 511 512 /** 513 * @hide 514 */ 515 public static final String KEY_PARAM_PITCH = "pitch"; 516 517 /** 518 * Parameter key to specify the audio stream type to be used when speaking text 519 * or playing back a file. The value should be one of the STREAM_ constants 520 * defined in {@link AudioManager}. 521 * 522 * @see TextToSpeech#speak(String, int, HashMap) 523 * @see TextToSpeech#playEarcon(String, int, HashMap) 524 */ 525 public static final String KEY_PARAM_STREAM = "streamType"; 526 527 /** 528 * Parameter key to specify the audio attributes to be used when 529 * speaking text or playing back a file. The value should be set 530 * using {@link TextToSpeech#setAudioAttributes(AudioAttributes)}. 531 * 532 * @see TextToSpeech#speak(String, int, HashMap) 533 * @see TextToSpeech#playEarcon(String, int, HashMap) 534 * @hide 535 */ 536 public static final String KEY_PARAM_AUDIO_ATTRIBUTES = "audioAttributes"; 537 538 /** 539 * Parameter key to identify an utterance in the 540 * {@link TextToSpeech.OnUtteranceCompletedListener} after text has been 541 * spoken, a file has been played back or a silence duration has elapsed. 542 * 543 * @see TextToSpeech#speak(String, int, HashMap) 544 * @see TextToSpeech#playEarcon(String, int, HashMap) 545 * @see TextToSpeech#synthesizeToFile(String, HashMap, String) 546 */ 547 public static final String KEY_PARAM_UTTERANCE_ID = "utteranceId"; 548 549 /** 550 * Parameter key to specify the speech volume relative to the current stream type 551 * volume used when speaking text. Volume is specified as a float ranging from 0 to 1 552 * where 0 is silence, and 1 is the maximum volume (the default behavior). 553 * 554 * @see TextToSpeech#speak(String, int, HashMap) 555 * @see TextToSpeech#playEarcon(String, int, HashMap) 556 */ 557 public static final String KEY_PARAM_VOLUME = "volume"; 558 559 /** 560 * Parameter key to specify how the speech is panned from left to right when speaking text. 561 * Pan is specified as a float ranging from -1 to +1 where -1 maps to a hard-left pan, 562 * 0 to center (the default behavior), and +1 to hard-right. 563 * 564 * @see TextToSpeech#speak(String, int, HashMap) 565 * @see TextToSpeech#playEarcon(String, int, HashMap) 566 */ 567 public static final String KEY_PARAM_PAN = "pan"; 568 569 /** 570 * Feature key for network synthesis. See {@link TextToSpeech#getFeatures(Locale)} 571 * for a description of how feature keys work. If set (and supported by the engine 572 * as per {@link TextToSpeech#getFeatures(Locale)}, the engine must 573 * use network based synthesis. 574 * 575 * @see TextToSpeech#speak(String, int, java.util.HashMap) 576 * @see TextToSpeech#synthesizeToFile(String, java.util.HashMap, String) 577 * @see TextToSpeech#getFeatures(java.util.Locale) 578 * 579 * @deprecated Starting from API level 20, to select network synthesis, call 580 * ({@link TextToSpeech#getVoices()}, find a suitable network voice 581 * ({@link Voice#getRequiresNetworkConnection()}) and pass it 582 * to {@link TextToSpeech#setVoice(Voice)}). 583 */ 584 @Deprecated 585 public static final String KEY_FEATURE_NETWORK_SYNTHESIS = "networkTts"; 586 587 /** 588 * Feature key for embedded synthesis. See {@link TextToSpeech#getFeatures(Locale)} 589 * for a description of how feature keys work. If set and supported by the engine 590 * as per {@link TextToSpeech#getFeatures(Locale)}, the engine must synthesize 591 * text on-device (without making network requests). 592 * 593 * @see TextToSpeech#speak(String, int, java.util.HashMap) 594 * @see TextToSpeech#synthesizeToFile(String, java.util.HashMap, String) 595 * @see TextToSpeech#getFeatures(java.util.Locale) 596 597 * @deprecated Starting from API level 20, to select embedded synthesis, call 598 * ({@link TextToSpeech#getVoices()}, find a suitable embedded voice 599 * ({@link Voice#getRequiresNetworkConnection()}) and pass it 600 * to {@link TextToSpeech#setVoice(Voice)}). 601 */ 602 @Deprecated 603 public static final String KEY_FEATURE_EMBEDDED_SYNTHESIS = "embeddedTts"; 604 605 /** 606 * Parameter key to specify an audio session identifier (obtained from 607 * {@link AudioManager#allocateAudioSessionId()}) that will be used by the request audio 608 * output. It can be used to associate one of the {@link android.media.audiofx.AudioEffect} 609 * objects with the synthesis (or earcon) output. 610 * 611 * @see TextToSpeech#speak(String, int, HashMap) 612 * @see TextToSpeech#playEarcon(String, int, HashMap) 613 */ 614 public static final String KEY_PARAM_SESSION_ID = "sessionId"; 615 616 /** 617 * Feature key that indicates that the voice may need to download additional data to be fully 618 * functional. The download will be triggered by calling 619 * {@link TextToSpeech#setVoice(Voice)} or {@link TextToSpeech#setLanguage(Locale)}. 620 * Until download is complete, each synthesis request will either report 621 * {@link TextToSpeech#ERROR_NOT_INSTALLED_YET} error, or use a different voice to synthesize 622 * the request. This feature should NOT be used as a key of a request parameter. 623 * 624 * @see TextToSpeech#getFeatures(java.util.Locale) 625 * @see Voice#getFeatures() 626 */ 627 public static final String KEY_FEATURE_NOT_INSTALLED = "notInstalled"; 628 629 /** 630 * Feature key that indicate that a network timeout can be set for the request. If set and 631 * supported as per {@link TextToSpeech#getFeatures(Locale)} or {@link Voice#getFeatures()}, 632 * it can be used as request parameter to set the maximum allowed time for a single 633 * request attempt, in milliseconds, before synthesis fails. When used as a key of 634 * a request parameter, its value should be a string with an integer value. 635 * 636 * @see TextToSpeech#getFeatures(java.util.Locale) 637 * @see Voice#getFeatures() 638 */ 639 public static final String KEY_FEATURE_NETWORK_TIMEOUT_MS = "networkTimeoutMs"; 640 641 /** 642 * Feature key that indicates that network request retries count can be set for the request. 643 * If set and supported as per {@link TextToSpeech#getFeatures(Locale)} or 644 * {@link Voice#getFeatures()}, it can be used as a request parameter to set the 645 * number of network request retries that are attempted in case of failure. When used as 646 * a key of a request parameter, its value should be a string with an integer value. 647 * 648 * @see TextToSpeech#getFeatures(java.util.Locale) 649 * @see Voice#getFeatures() 650 */ 651 public static final String KEY_FEATURE_NETWORK_RETRIES_COUNT = "networkRetriesCount"; 652 } 653 654 private final Context mContext; 655 private Connection mConnectingServiceConnection; 656 private Connection mServiceConnection; 657 private OnInitListener mInitListener; 658 // Written from an unspecified application thread, read from 659 // a binder thread. 660 private volatile UtteranceProgressListener mUtteranceProgressListener; 661 private final Object mStartLock = new Object(); 662 663 private String mRequestedEngine; 664 // Whether to initialize this TTS object with the default engine, 665 // if the requested engine is not available. Valid only if mRequestedEngine 666 // is not null. Used only for testing, though potentially useful API wise 667 // too. 668 private final boolean mUseFallback; 669 private final Map<String, Uri> mEarcons; 670 private final Map<CharSequence, Uri> mUtterances; 671 private final Bundle mParams = new Bundle(); 672 private final TtsEngines mEnginesHelper; 673 private volatile String mCurrentEngine = null; 674 675 /** 676 * The constructor for the TextToSpeech class, using the default TTS engine. 677 * This will also initialize the associated TextToSpeech engine if it isn't already running. 678 * 679 * @param context 680 * The context this instance is running in. 681 * @param listener 682 * The {@link TextToSpeech.OnInitListener} that will be called when the 683 * TextToSpeech engine has initialized. In a case of a failure the listener 684 * may be called immediately, before TextToSpeech instance is fully constructed. 685 */ 686 public TextToSpeech(Context context, OnInitListener listener) { 687 this(context, listener, null); 688 } 689 690 /** 691 * The constructor for the TextToSpeech class, using the given TTS engine. 692 * This will also initialize the associated TextToSpeech engine if it isn't already running. 693 * 694 * @param context 695 * The context this instance is running in. 696 * @param listener 697 * The {@link TextToSpeech.OnInitListener} that will be called when the 698 * TextToSpeech engine has initialized. In a case of a failure the listener 699 * may be called immediately, before TextToSpeech instance is fully constructed. 700 * @param engine Package name of the TTS engine to use. 701 */ 702 public TextToSpeech(Context context, OnInitListener listener, String engine) { 703 this(context, listener, engine, null, true); 704 } 705 706 /** 707 * Used by the framework to instantiate TextToSpeech objects with a supplied 708 * package name, instead of using {@link android.content.Context#getPackageName()} 709 * 710 * @hide 711 */ 712 public TextToSpeech(Context context, OnInitListener listener, String engine, 713 String packageName, boolean useFallback) { 714 mContext = context; 715 mInitListener = listener; 716 mRequestedEngine = engine; 717 mUseFallback = useFallback; 718 719 mEarcons = new HashMap<String, Uri>(); 720 mUtterances = new HashMap<CharSequence, Uri>(); 721 mUtteranceProgressListener = null; 722 723 mEnginesHelper = new TtsEngines(mContext); 724 initTts(); 725 } 726 727 private <R> R runActionNoReconnect(Action<R> action, R errorResult, String method, 728 boolean onlyEstablishedConnection) { 729 return runAction(action, errorResult, method, false, onlyEstablishedConnection); 730 } 731 732 private <R> R runAction(Action<R> action, R errorResult, String method) { 733 return runAction(action, errorResult, method, true, true); 734 } 735 736 private <R> R runAction(Action<R> action, R errorResult, String method, 737 boolean reconnect, boolean onlyEstablishedConnection) { 738 synchronized (mStartLock) { 739 if (mServiceConnection == null) { 740 Log.w(TAG, method + " failed: not bound to TTS engine"); 741 return errorResult; 742 } 743 return mServiceConnection.runAction(action, errorResult, method, reconnect, 744 onlyEstablishedConnection); 745 } 746 } 747 748 private int initTts() { 749 // Step 1: Try connecting to the engine that was requested. 750 if (mRequestedEngine != null) { 751 if (mEnginesHelper.isEngineInstalled(mRequestedEngine)) { 752 if (connectToEngine(mRequestedEngine)) { 753 mCurrentEngine = mRequestedEngine; 754 return SUCCESS; 755 } else if (!mUseFallback) { 756 mCurrentEngine = null; 757 dispatchOnInit(ERROR); 758 return ERROR; 759 } 760 } else if (!mUseFallback) { 761 Log.i(TAG, "Requested engine not installed: " + mRequestedEngine); 762 mCurrentEngine = null; 763 dispatchOnInit(ERROR); 764 return ERROR; 765 } 766 } 767 768 // Step 2: Try connecting to the user's default engine. 769 final String defaultEngine = getDefaultEngine(); 770 if (defaultEngine != null && !defaultEngine.equals(mRequestedEngine)) { 771 if (connectToEngine(defaultEngine)) { 772 mCurrentEngine = defaultEngine; 773 return SUCCESS; 774 } 775 } 776 777 // Step 3: Try connecting to the highest ranked engine in the 778 // system. 779 final String highestRanked = mEnginesHelper.getHighestRankedEngineName(); 780 if (highestRanked != null && !highestRanked.equals(mRequestedEngine) && 781 !highestRanked.equals(defaultEngine)) { 782 if (connectToEngine(highestRanked)) { 783 mCurrentEngine = highestRanked; 784 return SUCCESS; 785 } 786 } 787 788 // NOTE: The API currently does not allow the caller to query whether 789 // they are actually connected to any engine. This might fail for various 790 // reasons like if the user disables all her TTS engines. 791 792 mCurrentEngine = null; 793 dispatchOnInit(ERROR); 794 return ERROR; 795 } 796 797 private boolean connectToEngine(String engine) { 798 Connection connection = new Connection(); 799 Intent intent = new Intent(Engine.INTENT_ACTION_TTS_SERVICE); 800 intent.setPackage(engine); 801 boolean bound = mContext.bindService(intent, connection, Context.BIND_AUTO_CREATE); 802 if (!bound) { 803 Log.e(TAG, "Failed to bind to " + engine); 804 return false; 805 } else { 806 Log.i(TAG, "Sucessfully bound to " + engine); 807 mConnectingServiceConnection = connection; 808 return true; 809 } 810 } 811 812 private void dispatchOnInit(int result) { 813 synchronized (mStartLock) { 814 if (mInitListener != null) { 815 mInitListener.onInit(result); 816 mInitListener = null; 817 } 818 } 819 } 820 821 private IBinder getCallerIdentity() { 822 return mServiceConnection.getCallerIdentity(); 823 } 824 825 /** 826 * Releases the resources used by the TextToSpeech engine. 827 * It is good practice for instance to call this method in the onDestroy() method of an Activity 828 * so the TextToSpeech engine can be cleanly stopped. 829 */ 830 public void shutdown() { 831 // Special case, we are asked to shutdown connection that did finalize its connection. 832 synchronized (mStartLock) { 833 if (mConnectingServiceConnection != null) { 834 mContext.unbindService(mConnectingServiceConnection); 835 mConnectingServiceConnection = null; 836 return; 837 } 838 } 839 840 // Post connection case 841 runActionNoReconnect(new Action<Void>() { 842 @Override 843 public Void run(ITextToSpeechService service) throws RemoteException { 844 service.setCallback(getCallerIdentity(), null); 845 service.stop(getCallerIdentity()); 846 mServiceConnection.disconnect(); 847 // Context#unbindService does not result in a call to 848 // ServiceConnection#onServiceDisconnected. As a result, the 849 // service ends up being destroyed (if there are no other open 850 // connections to it) but the process lives on and the 851 // ServiceConnection continues to refer to the destroyed service. 852 // 853 // This leads to tons of log spam about SynthThread being dead. 854 mServiceConnection = null; 855 mCurrentEngine = null; 856 return null; 857 } 858 }, null, "shutdown", false); 859 } 860 861 /** 862 * Adds a mapping between a string of text and a sound resource in a 863 * package. After a call to this method, subsequent calls to 864 * {@link #speak(String, int, HashMap)} will play the specified sound resource 865 * if it is available, or synthesize the text it is missing. 866 * 867 * @param text 868 * The string of text. Example: <code>"south_south_east"</code> 869 * 870 * @param packagename 871 * Pass the packagename of the application that contains the 872 * resource. If the resource is in your own application (this is 873 * the most common case), then put the packagename of your 874 * application here.<br/> 875 * Example: <b>"com.google.marvin.compass"</b><br/> 876 * The packagename can be found in the AndroidManifest.xml of 877 * your application. 878 * <p> 879 * <code><manifest xmlns:android="..." 880 * package="<b>com.google.marvin.compass</b>"></code> 881 * </p> 882 * 883 * @param resourceId 884 * Example: <code>R.raw.south_south_east</code> 885 * 886 * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 887 */ 888 public int addSpeech(String text, String packagename, int resourceId) { 889 synchronized (mStartLock) { 890 mUtterances.put(text, makeResourceUri(packagename, resourceId)); 891 return SUCCESS; 892 } 893 } 894 895 /** 896 * Adds a mapping between a CharSequence (may be spanned with TtsSpans) of text 897 * and a sound resource in a package. After a call to this method, subsequent calls to 898 * {@link #speak(String, int, HashMap)} will play the specified sound resource 899 * if it is available, or synthesize the text it is missing. 900 * 901 * @param text 902 * The string of text. Example: <code>"south_south_east"</code> 903 * 904 * @param packagename 905 * Pass the packagename of the application that contains the 906 * resource. If the resource is in your own application (this is 907 * the most common case), then put the packagename of your 908 * application here.<br/> 909 * Example: <b>"com.google.marvin.compass"</b><br/> 910 * The packagename can be found in the AndroidManifest.xml of 911 * your application. 912 * <p> 913 * <code><manifest xmlns:android="..." 914 * package="<b>com.google.marvin.compass</b>"></code> 915 * </p> 916 * 917 * @param resourceId 918 * Example: <code>R.raw.south_south_east</code> 919 * 920 * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 921 */ 922 public int addSpeech(CharSequence text, String packagename, int resourceId) { 923 synchronized (mStartLock) { 924 mUtterances.put(text, makeResourceUri(packagename, resourceId)); 925 return SUCCESS; 926 } 927 } 928 929 /** 930 * Adds a mapping between a string of text and a sound file. Using this, it 931 * is possible to add custom pronounciations for a string of text. 932 * After a call to this method, subsequent calls to {@link #speak(String, int, HashMap)} 933 * will play the specified sound resource if it is available, or synthesize the text it is 934 * missing. 935 * 936 * @param text 937 * The string of text. Example: <code>"south_south_east"</code> 938 * @param filename 939 * The full path to the sound file (for example: 940 * "/sdcard/mysounds/hello.wav") 941 * 942 * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 943 */ 944 public int addSpeech(String text, String filename) { 945 synchronized (mStartLock) { 946 mUtterances.put(text, Uri.parse(filename)); 947 return SUCCESS; 948 } 949 } 950 951 /** 952 * Adds a mapping between a CharSequence (may be spanned with TtsSpans and a sound file. 953 * Using this, it is possible to add custom pronounciations for a string of text. 954 * After a call to this method, subsequent calls to {@link #speak(String, int, HashMap)} 955 * will play the specified sound resource if it is available, or synthesize the text it is 956 * missing. 957 * 958 * @param text 959 * The string of text. Example: <code>"south_south_east"</code> 960 * @param filename 961 * The full path to the sound file (for example: 962 * "/sdcard/mysounds/hello.wav") 963 * 964 * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 965 */ 966 public int addSpeech(CharSequence text, String filename) { 967 synchronized (mStartLock) { 968 mUtterances.put(text, Uri.parse(filename)); 969 return SUCCESS; 970 } 971 } 972 973 974 /** 975 * Adds a mapping between a string of text and a sound resource in a 976 * package. Use this to add custom earcons. 977 * 978 * @see #playEarcon(String, int, HashMap) 979 * 980 * @param earcon The name of the earcon. 981 * Example: <code>"[tick]"</code><br/> 982 * 983 * @param packagename 984 * the package name of the application that contains the 985 * resource. This can for instance be the package name of your own application. 986 * Example: <b>"com.google.marvin.compass"</b><br/> 987 * The package name can be found in the AndroidManifest.xml of 988 * the application containing the resource. 989 * <p> 990 * <code><manifest xmlns:android="..." 991 * package="<b>com.google.marvin.compass</b>"></code> 992 * </p> 993 * 994 * @param resourceId 995 * Example: <code>R.raw.tick_snd</code> 996 * 997 * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 998 */ 999 public int addEarcon(String earcon, String packagename, int resourceId) { 1000 synchronized(mStartLock) { 1001 mEarcons.put(earcon, makeResourceUri(packagename, resourceId)); 1002 return SUCCESS; 1003 } 1004 } 1005 1006 /** 1007 * Adds a mapping between a string of text and a sound file. 1008 * Use this to add custom earcons. 1009 * 1010 * @see #playEarcon(String, int, HashMap) 1011 * 1012 * @param earcon 1013 * The name of the earcon. 1014 * Example: <code>"[tick]"</code> 1015 * @param filename 1016 * The full path to the sound file (for example: 1017 * "/sdcard/mysounds/tick.wav") 1018 * 1019 * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 1020 */ 1021 public int addEarcon(String earcon, String filename) { 1022 synchronized(mStartLock) { 1023 mEarcons.put(earcon, Uri.parse(filename)); 1024 return SUCCESS; 1025 } 1026 } 1027 1028 private Uri makeResourceUri(String packageName, int resourceId) { 1029 return new Uri.Builder() 1030 .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) 1031 .encodedAuthority(packageName) 1032 .appendEncodedPath(String.valueOf(resourceId)) 1033 .build(); 1034 } 1035 1036 /** 1037 * Speaks the text using the specified queuing strategy and speech parameters, the text may 1038 * be spanned with TtsSpans. 1039 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 1040 * requests and then returns. The synthesis might not have finished (or even started!) at the 1041 * time when this method returns. In order to reliably detect errors during synthesis, 1042 * we recommend setting an utterance progress listener (see 1043 * {@link #setOnUtteranceProgressListener}) and using the 1044 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 1045 * 1046 * @param text The string of text to be spoken. No longer than 1047 * {@link #getMaxSpeechInputLength()} characters. 1048 * @param queueMode The queuing strategy to use, {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 1049 * @param params Parameters for the request. Can be null. 1050 * Supported parameter names: 1051 * {@link Engine#KEY_PARAM_STREAM}, 1052 * {@link Engine#KEY_PARAM_VOLUME}, 1053 * {@link Engine#KEY_PARAM_PAN}. 1054 * Engine specific parameters may be passed in but the parameter keys 1055 * must be prefixed by the name of the engine they are intended for. For example 1056 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 1057 * engine named "com.svox.pico" if it is being used. 1058 * @param utteranceId An unique identifier for this request. 1059 * 1060 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the speak operation. 1061 */ 1062 public int speak(final CharSequence text, 1063 final int queueMode, 1064 final HashMap<String, String> params, 1065 final String utteranceId) { 1066 return runAction(new Action<Integer>() { 1067 @Override 1068 public Integer run(ITextToSpeechService service) throws RemoteException { 1069 Uri utteranceUri = mUtterances.get(text); 1070 if (utteranceUri != null) { 1071 return service.playAudio(getCallerIdentity(), utteranceUri, queueMode, 1072 getParams(params), utteranceId); 1073 } else { 1074 return service.speak(getCallerIdentity(), text, queueMode, getParams(params), 1075 utteranceId); 1076 } 1077 } 1078 }, ERROR, "speak"); 1079 } 1080 1081 /** 1082 * Speaks the string using the specified queuing strategy and speech parameters. 1083 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 1084 * requests and then returns. The synthesis might not have finished (or even started!) at the 1085 * time when this method returns. In order to reliably detect errors during synthesis, 1086 * we recommend setting an utterance progress listener (see 1087 * {@link #setOnUtteranceProgressListener}) and using the 1088 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 1089 * 1090 * @param text The string of text to be spoken. No longer than 1091 * {@link #getMaxSpeechInputLength()} characters. 1092 * @param queueMode The queuing strategy to use, {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 1093 * @param params Parameters for the request. Can be null. 1094 * Supported parameter names: 1095 * {@link Engine#KEY_PARAM_STREAM}, 1096 * {@link Engine#KEY_PARAM_UTTERANCE_ID}, 1097 * {@link Engine#KEY_PARAM_VOLUME}, 1098 * {@link Engine#KEY_PARAM_PAN}. 1099 * Engine specific parameters may be passed in but the parameter keys 1100 * must be prefixed by the name of the engine they are intended for. For example 1101 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 1102 * engine named "com.svox.pico" if it is being used. 1103 * 1104 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the speak operation. 1105 * @deprecated As of API level 20, replaced by 1106 * {@link #speak(CharSequence, int, HashMap, String)}. 1107 */ 1108 @Deprecated 1109 public int speak(final String text, final int queueMode, final HashMap<String, String> params) { 1110 return speak(text, queueMode, params, 1111 params == null ? null : params.get(Engine.KEY_PARAM_UTTERANCE_ID)); 1112 } 1113 1114 /** 1115 * Plays the earcon using the specified queueing mode and parameters. 1116 * The earcon must already have been added with {@link #addEarcon(String, String)} or 1117 * {@link #addEarcon(String, String, int)}. 1118 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 1119 * requests and then returns. The synthesis might not have finished (or even started!) at the 1120 * time when this method returns. In order to reliably detect errors during synthesis, 1121 * we recommend setting an utterance progress listener (see 1122 * {@link #setOnUtteranceProgressListener}) and using the 1123 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 1124 * 1125 * @param earcon The earcon that should be played 1126 * @param queueMode {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 1127 * @param params Parameters for the request. Can be null. 1128 * Supported parameter names: 1129 * {@link Engine#KEY_PARAM_STREAM}, 1130 * Engine specific parameters may be passed in but the parameter keys 1131 * must be prefixed by the name of the engine they are intended for. For example 1132 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 1133 * engine named "com.svox.pico" if it is being used. 1134 * 1135 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the playEarcon operation. 1136 */ 1137 public int playEarcon(final String earcon, final int queueMode, 1138 final HashMap<String, String> params, final String utteranceId) { 1139 return runAction(new Action<Integer>() { 1140 @Override 1141 public Integer run(ITextToSpeechService service) throws RemoteException { 1142 Uri earconUri = mEarcons.get(earcon); 1143 if (earconUri == null) { 1144 return ERROR; 1145 } 1146 return service.playAudio(getCallerIdentity(), earconUri, queueMode, 1147 getParams(params), utteranceId); 1148 } 1149 }, ERROR, "playEarcon"); 1150 } 1151 1152 /** 1153 * Plays the earcon using the specified queueing mode and parameters. 1154 * The earcon must already have been added with {@link #addEarcon(String, String)} or 1155 * {@link #addEarcon(String, String, int)}. 1156 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 1157 * requests and then returns. The synthesis might not have finished (or even started!) at the 1158 * time when this method returns. In order to reliably detect errors during synthesis, 1159 * we recommend setting an utterance progress listener (see 1160 * {@link #setOnUtteranceProgressListener}) and using the 1161 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 1162 * 1163 * @param earcon The earcon that should be played 1164 * @param queueMode {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 1165 * @param params Parameters for the request. Can be null. 1166 * Supported parameter names: 1167 * {@link Engine#KEY_PARAM_STREAM}, 1168 * {@link Engine#KEY_PARAM_UTTERANCE_ID}. 1169 * Engine specific parameters may be passed in but the parameter keys 1170 * must be prefixed by the name of the engine they are intended for. For example 1171 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 1172 * engine named "com.svox.pico" if it is being used. 1173 * 1174 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the playEarcon operation. 1175 * @deprecated As of API level 20, replaced by 1176 * {@link #playEarcon(String, int, HashMap, String)}. 1177 */ 1178 @Deprecated 1179 public int playEarcon(final String earcon, final int queueMode, 1180 final HashMap<String, String> params) { 1181 return playEarcon(earcon, queueMode, params, 1182 params == null ? null : params.get(Engine.KEY_PARAM_UTTERANCE_ID)); 1183 } 1184 1185 /** 1186 * Plays silence for the specified amount of time using the specified 1187 * queue mode. 1188 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 1189 * requests and then returns. The synthesis might not have finished (or even started!) at the 1190 * time when this method returns. In order to reliably detect errors during synthesis, 1191 * we recommend setting an utterance progress listener (see 1192 * {@link #setOnUtteranceProgressListener}) and using the 1193 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 1194 * 1195 * @param durationInMs The duration of the silence. 1196 * @param queueMode {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 1197 * @param params Parameters for the request. Can be null. 1198 * Engine specific parameters may be passed in but the parameter keys 1199 * must be prefixed by the name of the engine they are intended for. For example 1200 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 1201 * engine named "com.svox.pico" if it is being used. 1202 * @param utteranceId An unique identifier for this request. 1203 * 1204 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the playSilence operation. 1205 */ 1206 public int playSilence(final long durationInMs, final int queueMode, 1207 final HashMap<String, String> params, final String utteranceId) { 1208 return runAction(new Action<Integer>() { 1209 @Override 1210 public Integer run(ITextToSpeechService service) throws RemoteException { 1211 return service.playSilence(getCallerIdentity(), durationInMs, 1212 queueMode, utteranceId); 1213 } 1214 }, ERROR, "playSilence"); 1215 } 1216 1217 /** 1218 * Plays silence for the specified amount of time using the specified 1219 * queue mode. 1220 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 1221 * requests and then returns. The synthesis might not have finished (or even started!) at the 1222 * time when this method returns. In order to reliably detect errors during synthesis, 1223 * we recommend setting an utterance progress listener (see 1224 * {@link #setOnUtteranceProgressListener}) and using the 1225 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 1226 * 1227 * @param durationInMs The duration of the silence. 1228 * @param queueMode {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 1229 * @param params Parameters for the request. Can be null. 1230 * Supported parameter names: 1231 * {@link Engine#KEY_PARAM_UTTERANCE_ID}. 1232 * Engine specific parameters may be passed in but the parameter keys 1233 * must be prefixed by the name of the engine they are intended for. For example 1234 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 1235 * engine named "com.svox.pico" if it is being used. 1236 * 1237 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the playSilence operation. 1238 * @deprecated As of API level 20, replaced by 1239 * {@link #playSilence(long, int, HashMap, String)}. 1240 */ 1241 @Deprecated 1242 public int playSilence(final long durationInMs, final int queueMode, 1243 final HashMap<String, String> params) { 1244 return playSilence(durationInMs, queueMode, params, 1245 params == null ? null : params.get(Engine.KEY_PARAM_UTTERANCE_ID)); 1246 } 1247 1248 /** 1249 * Queries the engine for the set of features it supports for a given locale. 1250 * Features can either be framework defined, e.g. 1251 * {@link TextToSpeech.Engine#KEY_FEATURE_NETWORK_SYNTHESIS} or engine specific. 1252 * Engine specific keys must be prefixed by the name of the engine they 1253 * are intended for. These keys can be used as parameters to 1254 * {@link TextToSpeech#speak(String, int, java.util.HashMap)} and 1255 * {@link TextToSpeech#synthesizeToFile(String, java.util.HashMap, String)}. 1256 * 1257 * Features values are strings and their values must meet restrictions described in their 1258 * documentation. 1259 * 1260 * @param locale The locale to query features for. 1261 * @return Set instance. May return {@code null} on error. 1262 * @deprecated As of API level 20, please use voices. In order to query features of the voice, 1263 * call {@link #getVoices()} to retrieve the list of available voices and 1264 * {@link Voice#getFeatures()} to retrieve the set of features. 1265 */ 1266 @Deprecated 1267 public Set<String> getFeatures(final Locale locale) { 1268 return runAction(new Action<Set<String>>() { 1269 @Override 1270 public Set<String> run(ITextToSpeechService service) throws RemoteException { 1271 String[] features = null; 1272 try { 1273 features = service.getFeaturesForLanguage( 1274 locale.getISO3Language(), locale.getISO3Country(), locale.getVariant()); 1275 } catch(MissingResourceException e) { 1276 Log.w(TAG, "Couldn't retrieve 3 letter ISO 639-2/T language and/or ISO 3166 " + 1277 "country code for locale: " + locale, e); 1278 return null; 1279 } 1280 1281 if (features != null) { 1282 final Set<String> featureSet = new HashSet<String>(); 1283 Collections.addAll(featureSet, features); 1284 return featureSet; 1285 } 1286 return null; 1287 } 1288 }, null, "getFeatures"); 1289 } 1290 1291 /** 1292 * Checks whether the TTS engine is busy speaking. Note that a speech item is 1293 * considered complete once it's audio data has been sent to the audio mixer, or 1294 * written to a file. There might be a finite lag between this point, and when 1295 * the audio hardware completes playback. 1296 * 1297 * @return {@code true} if the TTS engine is speaking. 1298 */ 1299 public boolean isSpeaking() { 1300 return runAction(new Action<Boolean>() { 1301 @Override 1302 public Boolean run(ITextToSpeechService service) throws RemoteException { 1303 return service.isSpeaking(); 1304 } 1305 }, false, "isSpeaking"); 1306 } 1307 1308 /** 1309 * Interrupts the current utterance (whether played or rendered to file) and discards other 1310 * utterances in the queue. 1311 * 1312 * @return {@link #ERROR} or {@link #SUCCESS}. 1313 */ 1314 public int stop() { 1315 return runAction(new Action<Integer>() { 1316 @Override 1317 public Integer run(ITextToSpeechService service) throws RemoteException { 1318 return service.stop(getCallerIdentity()); 1319 } 1320 }, ERROR, "stop"); 1321 } 1322 1323 /** 1324 * Sets the speech rate. 1325 * 1326 * This has no effect on any pre-recorded speech. 1327 * 1328 * @param speechRate Speech rate. {@code 1.0} is the normal speech rate, 1329 * lower values slow down the speech ({@code 0.5} is half the normal speech rate), 1330 * greater values accelerate it ({@code 2.0} is twice the normal speech rate). 1331 * 1332 * @return {@link #ERROR} or {@link #SUCCESS}. 1333 */ 1334 public int setSpeechRate(float speechRate) { 1335 if (speechRate > 0.0f) { 1336 int intRate = (int)(speechRate * 100); 1337 if (intRate > 0) { 1338 synchronized (mStartLock) { 1339 mParams.putInt(Engine.KEY_PARAM_RATE, intRate); 1340 } 1341 return SUCCESS; 1342 } 1343 } 1344 return ERROR; 1345 } 1346 1347 /** 1348 * Sets the speech pitch for the TextToSpeech engine. 1349 * 1350 * This has no effect on any pre-recorded speech. 1351 * 1352 * @param pitch Speech pitch. {@code 1.0} is the normal pitch, 1353 * lower values lower the tone of the synthesized voice, 1354 * greater values increase it. 1355 * 1356 * @return {@link #ERROR} or {@link #SUCCESS}. 1357 */ 1358 public int setPitch(float pitch) { 1359 if (pitch > 0.0f) { 1360 int intPitch = (int)(pitch * 100); 1361 if (intPitch > 0) { 1362 synchronized (mStartLock) { 1363 mParams.putInt(Engine.KEY_PARAM_PITCH, intPitch); 1364 } 1365 return SUCCESS; 1366 } 1367 } 1368 return ERROR; 1369 } 1370 1371 /** 1372 * Sets the audio attributes to be used when speaking text or playing 1373 * back a file. 1374 * 1375 * @param audioAttributes Valid AudioAttributes instance. 1376 * 1377 * @return {@link #ERROR} or {@link #SUCCESS}. 1378 */ 1379 public int setAudioAttributes(AudioAttributes audioAttributes) { 1380 if (audioAttributes != null) { 1381 synchronized (mStartLock) { 1382 mParams.putParcelable(Engine.KEY_PARAM_AUDIO_ATTRIBUTES, 1383 audioAttributes); 1384 } 1385 return SUCCESS; 1386 } 1387 return ERROR; 1388 } 1389 1390 /** 1391 * @return the engine currently in use by this TextToSpeech instance. 1392 * @hide 1393 */ 1394 public String getCurrentEngine() { 1395 return mCurrentEngine; 1396 } 1397 1398 /** 1399 * Returns a Locale instance describing the language currently being used as the default 1400 * Text-to-speech language. 1401 * 1402 * The locale object returned by this method is NOT a valid one. It has identical form to the 1403 * one in {@link #getLanguage()}. Please refer to {@link #getLanguage()} for more information. 1404 * 1405 * @return language, country (if any) and variant (if any) used by the client stored in a 1406 * Locale instance, or {@code null} on error. 1407 * @deprecated As of API Level 20, use <code>getDefaultVoice().getLocale()</code> ({@link 1408 * #getDefaultVoice()}) 1409 */ 1410 @Deprecated 1411 public Locale getDefaultLanguage() { 1412 return runAction(new Action<Locale>() { 1413 @Override 1414 public Locale run(ITextToSpeechService service) throws RemoteException { 1415 String[] defaultLanguage = service.getClientDefaultLanguage(); 1416 1417 return new Locale(defaultLanguage[0], defaultLanguage[1], defaultLanguage[2]); 1418 } 1419 }, null, "getDefaultLanguage"); 1420 } 1421 1422 /** 1423 * Sets the text-to-speech language. 1424 * The TTS engine will try to use the closest match to the specified 1425 * language as represented by the Locale, but there is no guarantee that the exact same Locale 1426 * will be used. Use {@link #isLanguageAvailable(Locale)} to check the level of support 1427 * before choosing the language to use for the next utterances. 1428 * 1429 * This method sets the current voice to the default one for the given Locale; 1430 * {@link #getVoice()} can be used to retrieve it. 1431 * 1432 * @param loc The locale describing the language to be used. 1433 * 1434 * @return Code indicating the support status for the locale. See {@link #LANG_AVAILABLE}, 1435 * {@link #LANG_COUNTRY_AVAILABLE}, {@link #LANG_COUNTRY_VAR_AVAILABLE}, 1436 * {@link #LANG_MISSING_DATA} and {@link #LANG_NOT_SUPPORTED}. 1437 */ 1438 public int setLanguage(final Locale loc) { 1439 return runAction(new Action<Integer>() { 1440 @Override 1441 public Integer run(ITextToSpeechService service) throws RemoteException { 1442 if (loc == null) { 1443 return LANG_NOT_SUPPORTED; 1444 } 1445 String language = null, country = null; 1446 try { 1447 language = loc.getISO3Language(); 1448 } catch (MissingResourceException e) { 1449 Log.w(TAG, "Couldn't retrieve ISO 639-2/T language code for locale: " + loc, e); 1450 return LANG_NOT_SUPPORTED; 1451 } 1452 1453 try { 1454 country = loc.getISO3Country(); 1455 } catch (MissingResourceException e) { 1456 Log.w(TAG, "Couldn't retrieve ISO 3166 country code for locale: " + loc, e); 1457 return LANG_NOT_SUPPORTED; 1458 } 1459 1460 String variant = loc.getVariant(); 1461 1462 // As of API level 20, setLanguage is implemented using setVoice. 1463 // (which, in the default implementation, will call loadLanguage on the service 1464 // interface). 1465 1466 // Sanitize locale using isLanguageAvailable. 1467 int result = service.isLanguageAvailable( language, country, variant); 1468 if (result >= LANG_AVAILABLE){ 1469 if (result < LANG_COUNTRY_VAR_AVAILABLE) { 1470 variant = ""; 1471 if (result < LANG_COUNTRY_AVAILABLE) { 1472 country = ""; 1473 } 1474 } 1475 // Get the default voice for the locale. 1476 String voiceName = service.getDefaultVoiceNameFor(language, country, variant); 1477 if (TextUtils.isEmpty(voiceName)) { 1478 Log.w(TAG, "Couldn't find the default voice for " + language + "/" + 1479 country + "/" + variant); 1480 return LANG_NOT_SUPPORTED; 1481 } 1482 1483 // Load it. 1484 if (service.loadVoice(getCallerIdentity(), voiceName) == TextToSpeech.ERROR) { 1485 return LANG_NOT_SUPPORTED; 1486 } 1487 1488 mParams.putString(Engine.KEY_PARAM_VOICE_NAME, voiceName); 1489 mParams.putString(Engine.KEY_PARAM_LANGUAGE, language); 1490 mParams.putString(Engine.KEY_PARAM_COUNTRY, country); 1491 mParams.putString(Engine.KEY_PARAM_VARIANT, variant); 1492 } 1493 return result; 1494 } 1495 }, LANG_NOT_SUPPORTED, "setLanguage"); 1496 } 1497 1498 /** 1499 * Returns a Locale instance describing the language currently being used for synthesis 1500 * requests sent to the TextToSpeech engine. 1501 * 1502 * In Android 4.2 and before (API <= 17) this function returns the language that is currently 1503 * being used by the TTS engine. That is the last language set by this or any other 1504 * client by a {@link TextToSpeech#setLanguage} call to the same engine. 1505 * 1506 * In Android versions after 4.2 this function returns the language that is currently being 1507 * used for the synthesis requests sent from this client. That is the last language set 1508 * by a {@link TextToSpeech#setLanguage} call on this instance. 1509 * 1510 * If a voice is set (by {@link #setVoice(Voice)}), getLanguage will return the language of 1511 * the currently set voice. 1512 * 1513 * Please note that the Locale object returned by this method is NOT a valid Locale object. Its 1514 * language field contains a three-letter ISO 639-2/T code (where a proper Locale would use 1515 * a two-letter ISO 639-1 code), and the country field contains a three-letter ISO 3166 country 1516 * code (where a proper Locale would use a two-letter ISO 3166-1 code). 1517 * 1518 * @return language, country (if any) and variant (if any) used by the client stored in a 1519 * Locale instance, or {@code null} on error. 1520 * 1521 * @deprecated As of API level 20, please use <code>getVoice().getLocale()</code> 1522 * ({@link #getVoice()}). 1523 */ 1524 @Deprecated 1525 public Locale getLanguage() { 1526 return runAction(new Action<Locale>() { 1527 @Override 1528 public Locale run(ITextToSpeechService service) { 1529 /* No service call, but we're accessing mParams, hence need for 1530 wrapping it as an Action instance */ 1531 String lang = mParams.getString(Engine.KEY_PARAM_LANGUAGE, ""); 1532 String country = mParams.getString(Engine.KEY_PARAM_COUNTRY, ""); 1533 String variant = mParams.getString(Engine.KEY_PARAM_VARIANT, ""); 1534 return new Locale(lang, country, variant); 1535 } 1536 }, null, "getLanguage"); 1537 } 1538 1539 /** 1540 * Query the engine about the set of available languages. 1541 */ 1542 public Set<Locale> getAvailableLanguages() { 1543 return runAction(new Action<Set<Locale>>() { 1544 @Override 1545 public Set<Locale> run(ITextToSpeechService service) throws RemoteException { 1546 List<Voice> voices = service.getVoices(); 1547 if (voices != null) { 1548 return new TreeSet<Locale>(); 1549 } 1550 TreeSet<Locale> locales = new TreeSet<Locale>(); 1551 for (Voice voice : voices) { 1552 locales.add(voice.getLocale()); 1553 } 1554 return locales; 1555 } 1556 }, null, "getAvailableLanguages"); 1557 } 1558 1559 /** 1560 * Query the engine about the set of available voices. 1561 * 1562 * Each TTS Engine can expose multiple voices for each locale, each with a different set of 1563 * features. 1564 * 1565 * @see #setVoice(Voice) 1566 * @see Voice 1567 */ 1568 public Set<Voice> getVoices() { 1569 return runAction(new Action<Set<Voice>>() { 1570 @Override 1571 public Set<Voice> run(ITextToSpeechService service) throws RemoteException { 1572 List<Voice> voices = service.getVoices(); 1573 return (voices != null) ? new TreeSet<Voice>(voices) : new TreeSet<Voice>(); 1574 } 1575 }, null, "getVoices"); 1576 } 1577 1578 /** 1579 * Sets the text-to-speech voice. 1580 * 1581 * @param voice One of objects returned by {@link #getVoices()}. 1582 * 1583 * @return {@link #ERROR} or {@link #SUCCESS}. 1584 * 1585 * @see #getVoices 1586 * @see Voice 1587 */ 1588 public int setVoice(final Voice voice) { 1589 return runAction(new Action<Integer>() { 1590 @Override 1591 public Integer run(ITextToSpeechService service) throws RemoteException { 1592 int result = service.loadVoice(getCallerIdentity(), voice.getName()); 1593 if (result == SUCCESS) { 1594 mParams.putString(Engine.KEY_PARAM_VOICE_NAME, voice.getName()); 1595 1596 // Set the language/country/variant, so #getLanguage will return the voice 1597 // locale when called. 1598 String language = ""; 1599 try { 1600 language = voice.getLocale().getISO3Language(); 1601 } catch (MissingResourceException e) { 1602 Log.w(TAG, "Couldn't retrieve ISO 639-2/T language code for locale: " + 1603 voice.getLocale(), e); 1604 } 1605 1606 String country = ""; 1607 try { 1608 country = voice.getLocale().getISO3Country(); 1609 } catch (MissingResourceException e) { 1610 Log.w(TAG, "Couldn't retrieve ISO 3166 country code for locale: " + 1611 voice.getLocale(), e); 1612 } 1613 mParams.putString(Engine.KEY_PARAM_LANGUAGE, language); 1614 mParams.putString(Engine.KEY_PARAM_COUNTRY, country); 1615 mParams.putString(Engine.KEY_PARAM_VARIANT, voice.getLocale().getVariant()); 1616 } 1617 return result; 1618 } 1619 }, LANG_NOT_SUPPORTED, "setVoice"); 1620 } 1621 1622 /** 1623 * Returns a Voice instance describing the voice currently being used for synthesis 1624 * requests sent to the TextToSpeech engine. 1625 * 1626 * @return Voice instance used by the client, or {@code null} if not set or on error. 1627 * 1628 * @see #getVoices 1629 * @see #setVoice 1630 * @see Voice 1631 */ 1632 public Voice getVoice() { 1633 return runAction(new Action<Voice>() { 1634 @Override 1635 public Voice run(ITextToSpeechService service) throws RemoteException { 1636 String voiceName = mParams.getString(Engine.KEY_PARAM_VOICE_NAME, ""); 1637 if (TextUtils.isEmpty(voiceName)) { 1638 return null; 1639 } 1640 List<Voice> voices = service.getVoices(); 1641 if (voices == null) { 1642 return null; 1643 } 1644 for (Voice voice : voices) { 1645 if (voice.getName().equals(voiceName)) { 1646 return voice; 1647 } 1648 } 1649 return null; 1650 } 1651 }, null, "getVoice"); 1652 } 1653 1654 /** 1655 * Returns a Voice instance that's the default voice for the default Text-to-speech language. 1656 * @return The default voice instance for the default language, or {@code null} if not set or 1657 * on error. 1658 */ 1659 public Voice getDefaultVoice() { 1660 return runAction(new Action<Voice>() { 1661 @Override 1662 public Voice run(ITextToSpeechService service) throws RemoteException { 1663 1664 String[] defaultLanguage = service.getClientDefaultLanguage(); 1665 1666 if (defaultLanguage == null || defaultLanguage.length == 0) { 1667 Log.e(TAG, "service.getClientDefaultLanguage() returned empty array"); 1668 return null; 1669 } 1670 String language = defaultLanguage[0]; 1671 String country = (defaultLanguage.length > 1) ? defaultLanguage[1] : ""; 1672 String variant = (defaultLanguage.length > 2) ? defaultLanguage[2] : ""; 1673 1674 // Sanitize the locale using isLanguageAvailable. 1675 int result = service.isLanguageAvailable(language, country, variant); 1676 if (result >= LANG_AVAILABLE){ 1677 if (result < LANG_COUNTRY_VAR_AVAILABLE) { 1678 variant = ""; 1679 if (result < LANG_COUNTRY_AVAILABLE) { 1680 country = ""; 1681 } 1682 } 1683 } else { 1684 // The default language is not supported. 1685 return null; 1686 } 1687 1688 // Get the default voice name 1689 String voiceName = service.getDefaultVoiceNameFor(language, country, variant); 1690 if (TextUtils.isEmpty(voiceName)) { 1691 return null; 1692 } 1693 1694 // Find it 1695 List<Voice> voices = service.getVoices(); 1696 if (voices == null) { 1697 return null; 1698 } 1699 for (Voice voice : voices) { 1700 if (voice.getName().equals(voiceName)) { 1701 return voice; 1702 } 1703 } 1704 return null; 1705 } 1706 }, null, "getDefaultVoice"); 1707 } 1708 1709 1710 1711 /** 1712 * Checks if the specified language as represented by the Locale is available and supported. 1713 * 1714 * @param loc The Locale describing the language to be used. 1715 * 1716 * @return Code indicating the support status for the locale. See {@link #LANG_AVAILABLE}, 1717 * {@link #LANG_COUNTRY_AVAILABLE}, {@link #LANG_COUNTRY_VAR_AVAILABLE}, 1718 * {@link #LANG_MISSING_DATA} and {@link #LANG_NOT_SUPPORTED}. 1719 */ 1720 public int isLanguageAvailable(final Locale loc) { 1721 return runAction(new Action<Integer>() { 1722 @Override 1723 public Integer run(ITextToSpeechService service) throws RemoteException { 1724 String language = null, country = null; 1725 1726 try { 1727 language = loc.getISO3Language(); 1728 } catch (MissingResourceException e) { 1729 Log.w(TAG, "Couldn't retrieve ISO 639-2/T language code for locale: " + loc, e); 1730 return LANG_NOT_SUPPORTED; 1731 } 1732 1733 try { 1734 country = loc.getISO3Country(); 1735 } catch (MissingResourceException e) { 1736 Log.w(TAG, "Couldn't retrieve ISO 3166 country code for locale: " + loc, e); 1737 return LANG_NOT_SUPPORTED; 1738 } 1739 1740 return service.isLanguageAvailable(language, country, loc.getVariant()); 1741 } 1742 }, LANG_NOT_SUPPORTED, "isLanguageAvailable"); 1743 } 1744 1745 /** 1746 * Synthesizes the given text to a file using the specified parameters. 1747 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 1748 * requests and then returns. The synthesis might not have finished (or even started!) at the 1749 * time when this method returns. In order to reliably detect errors during synthesis, 1750 * we recommend setting an utterance progress listener (see 1751 * {@link #setOnUtteranceProgressListener}). 1752 * 1753 * @param text The text that should be synthesized. No longer than 1754 * {@link #getMaxSpeechInputLength()} characters. 1755 * @param params Parameters for the request. Can be null. 1756 * Engine specific parameters may be passed in but the parameter keys 1757 * must be prefixed by the name of the engine they are intended for. For example 1758 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 1759 * engine named "com.svox.pico" if it is being used. 1760 * @param filename Absolute file filename to write the generated audio data to.It should be 1761 * something like "/sdcard/myappsounds/mysound.wav". 1762 * @param utteranceId An unique identifier for this request. 1763 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the synthesizeToFile operation. 1764 */ 1765 public int synthesizeToFile(final CharSequence text, final HashMap<String, String> params, 1766 final String filename, final String utteranceId) { 1767 return runAction(new Action<Integer>() { 1768 @Override 1769 public Integer run(ITextToSpeechService service) throws RemoteException { 1770 ParcelFileDescriptor fileDescriptor; 1771 int returnValue; 1772 try { 1773 File file = new File(filename); 1774 if(file.exists() && !file.canWrite()) { 1775 Log.e(TAG, "Can't write to " + filename); 1776 return ERROR; 1777 } 1778 fileDescriptor = ParcelFileDescriptor.open(file, 1779 ParcelFileDescriptor.MODE_WRITE_ONLY | 1780 ParcelFileDescriptor.MODE_CREATE | 1781 ParcelFileDescriptor.MODE_TRUNCATE); 1782 returnValue = service.synthesizeToFileDescriptor(getCallerIdentity(), text, 1783 fileDescriptor, getParams(params), utteranceId); 1784 fileDescriptor.close(); 1785 return returnValue; 1786 } catch (FileNotFoundException e) { 1787 Log.e(TAG, "Opening file " + filename + " failed", e); 1788 return ERROR; 1789 } catch (IOException e) { 1790 Log.e(TAG, "Closing file " + filename + " failed", e); 1791 return ERROR; 1792 } 1793 } 1794 }, ERROR, "synthesizeToFile"); 1795 } 1796 1797 /** 1798 * Synthesizes the given text to a file using the specified parameters. 1799 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 1800 * requests and then returns. The synthesis might not have finished (or even started!) at the 1801 * time when this method returns. In order to reliably detect errors during synthesis, 1802 * we recommend setting an utterance progress listener (see 1803 * {@link #setOnUtteranceProgressListener}) and using the 1804 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 1805 * 1806 * @param text The text that should be synthesized. No longer than 1807 * {@link #getMaxSpeechInputLength()} characters. 1808 * @param params Parameters for the request. Can be null. 1809 * Supported parameter names: 1810 * {@link Engine#KEY_PARAM_UTTERANCE_ID}. 1811 * Engine specific parameters may be passed in but the parameter keys 1812 * must be prefixed by the name of the engine they are intended for. For example 1813 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 1814 * engine named "com.svox.pico" if it is being used. 1815 * @param filename Absolute file filename to write the generated audio data to.It should be 1816 * something like "/sdcard/myappsounds/mysound.wav". 1817 * 1818 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the synthesizeToFile operation. 1819 * @deprecated As of API level 20, replaced by 1820 * {@link #synthesizeToFile(CharSequence, HashMap, String, String)}. 1821 */ 1822 public int synthesizeToFile(final String text, final HashMap<String, String> params, 1823 final String filename) { 1824 return synthesizeToFile(text, params, filename, params.get(Engine.KEY_PARAM_UTTERANCE_ID)); 1825 } 1826 1827 private Bundle getParams(HashMap<String, String> params) { 1828 if (params != null && !params.isEmpty()) { 1829 Bundle bundle = new Bundle(mParams); 1830 copyIntParam(bundle, params, Engine.KEY_PARAM_STREAM); 1831 copyIntParam(bundle, params, Engine.KEY_PARAM_SESSION_ID); 1832 copyStringParam(bundle, params, Engine.KEY_PARAM_UTTERANCE_ID); 1833 copyFloatParam(bundle, params, Engine.KEY_PARAM_VOLUME); 1834 copyFloatParam(bundle, params, Engine.KEY_PARAM_PAN); 1835 1836 // Copy feature strings defined by the framework. 1837 copyStringParam(bundle, params, Engine.KEY_FEATURE_NETWORK_SYNTHESIS); 1838 copyStringParam(bundle, params, Engine.KEY_FEATURE_EMBEDDED_SYNTHESIS); 1839 copyIntParam(bundle, params, Engine.KEY_FEATURE_NETWORK_TIMEOUT_MS); 1840 copyIntParam(bundle, params, Engine.KEY_FEATURE_NETWORK_RETRIES_COUNT); 1841 1842 // Copy over all parameters that start with the name of the 1843 // engine that we are currently connected to. The engine is 1844 // free to interpret them as it chooses. 1845 if (!TextUtils.isEmpty(mCurrentEngine)) { 1846 for (Map.Entry<String, String> entry : params.entrySet()) { 1847 final String key = entry.getKey(); 1848 if (key != null && key.startsWith(mCurrentEngine)) { 1849 bundle.putString(key, entry.getValue()); 1850 } 1851 } 1852 } 1853 1854 return bundle; 1855 } else { 1856 return mParams; 1857 } 1858 } 1859 1860 private void copyStringParam(Bundle bundle, HashMap<String, String> params, String key) { 1861 String value = params.get(key); 1862 if (value != null) { 1863 bundle.putString(key, value); 1864 } 1865 } 1866 1867 private void copyIntParam(Bundle bundle, HashMap<String, String> params, String key) { 1868 String valueString = params.get(key); 1869 if (!TextUtils.isEmpty(valueString)) { 1870 try { 1871 int value = Integer.parseInt(valueString); 1872 bundle.putInt(key, value); 1873 } catch (NumberFormatException ex) { 1874 // don't set the value in the bundle 1875 } 1876 } 1877 } 1878 1879 private void copyFloatParam(Bundle bundle, HashMap<String, String> params, String key) { 1880 String valueString = params.get(key); 1881 if (!TextUtils.isEmpty(valueString)) { 1882 try { 1883 float value = Float.parseFloat(valueString); 1884 bundle.putFloat(key, value); 1885 } catch (NumberFormatException ex) { 1886 // don't set the value in the bundle 1887 } 1888 } 1889 } 1890 1891 /** 1892 * Sets the listener that will be notified when synthesis of an utterance completes. 1893 * 1894 * @param listener The listener to use. 1895 * 1896 * @return {@link #ERROR} or {@link #SUCCESS}. 1897 * 1898 * @deprecated Use {@link #setOnUtteranceProgressListener(UtteranceProgressListener)} 1899 * instead. 1900 */ 1901 @Deprecated 1902 public int setOnUtteranceCompletedListener(final OnUtteranceCompletedListener listener) { 1903 mUtteranceProgressListener = UtteranceProgressListener.from(listener); 1904 return TextToSpeech.SUCCESS; 1905 } 1906 1907 /** 1908 * Sets the listener that will be notified of various events related to the 1909 * synthesis of a given utterance. 1910 * 1911 * See {@link UtteranceProgressListener} and 1912 * {@link TextToSpeech.Engine#KEY_PARAM_UTTERANCE_ID}. 1913 * 1914 * @param listener the listener to use. 1915 * @return {@link #ERROR} or {@link #SUCCESS} 1916 */ 1917 public int setOnUtteranceProgressListener(UtteranceProgressListener listener) { 1918 mUtteranceProgressListener = listener; 1919 return TextToSpeech.SUCCESS; 1920 } 1921 1922 /** 1923 * Sets the TTS engine to use. 1924 * 1925 * @deprecated This doesn't inform callers when the TTS engine has been 1926 * initialized. {@link #TextToSpeech(Context, OnInitListener, String)} 1927 * can be used with the appropriate engine name. Also, there is no 1928 * guarantee that the engine specified will be loaded. If it isn't 1929 * installed or disabled, the user / system wide defaults will apply. 1930 * 1931 * @param enginePackageName The package name for the synthesis engine (e.g. "com.svox.pico") 1932 * 1933 * @return {@link #ERROR} or {@link #SUCCESS}. 1934 */ 1935 @Deprecated 1936 public int setEngineByPackageName(String enginePackageName) { 1937 mRequestedEngine = enginePackageName; 1938 return initTts(); 1939 } 1940 1941 /** 1942 * Gets the package name of the default speech synthesis engine. 1943 * 1944 * @return Package name of the TTS engine that the user has chosen 1945 * as their default. 1946 */ 1947 public String getDefaultEngine() { 1948 return mEnginesHelper.getDefaultEngine(); 1949 } 1950 1951 /** 1952 * Checks whether the user's settings should override settings requested 1953 * by the calling application. As of the Ice cream sandwich release, 1954 * user settings never forcibly override the app's settings. 1955 */ 1956 @Deprecated 1957 public boolean areDefaultsEnforced() { 1958 return false; 1959 } 1960 1961 /** 1962 * Gets a list of all installed TTS engines. 1963 * 1964 * @return A list of engine info objects. The list can be empty, but never {@code null}. 1965 */ 1966 public List<EngineInfo> getEngines() { 1967 return mEnginesHelper.getEngines(); 1968 } 1969 1970 private class Connection implements ServiceConnection { 1971 private ITextToSpeechService mService; 1972 1973 private SetupConnectionAsyncTask mOnSetupConnectionAsyncTask; 1974 1975 private boolean mEstablished; 1976 1977 private final ITextToSpeechCallback.Stub mCallback = new ITextToSpeechCallback.Stub() { 1978 public void onStop(String utteranceId) throws RemoteException { 1979 UtteranceProgressListener listener = mUtteranceProgressListener; 1980 if (listener != null) { 1981 listener.onDone(utteranceId); 1982 } 1983 }; 1984 1985 @Override 1986 public void onSuccess(String utteranceId) { 1987 UtteranceProgressListener listener = mUtteranceProgressListener; 1988 if (listener != null) { 1989 listener.onDone(utteranceId); 1990 } 1991 } 1992 1993 @Override 1994 public void onError(String utteranceId, int errorCode) { 1995 UtteranceProgressListener listener = mUtteranceProgressListener; 1996 if (listener != null) { 1997 listener.onError(utteranceId); 1998 } 1999 } 2000 2001 @Override 2002 public void onStart(String utteranceId) { 2003 UtteranceProgressListener listener = mUtteranceProgressListener; 2004 if (listener != null) { 2005 listener.onStart(utteranceId); 2006 } 2007 } 2008 }; 2009 2010 private class SetupConnectionAsyncTask extends AsyncTask<Void, Void, Integer> { 2011 private final ComponentName mName; 2012 2013 public SetupConnectionAsyncTask(ComponentName name) { 2014 mName = name; 2015 } 2016 2017 @Override 2018 protected Integer doInBackground(Void... params) { 2019 synchronized(mStartLock) { 2020 if (isCancelled()) { 2021 return null; 2022 } 2023 2024 try { 2025 mService.setCallback(getCallerIdentity(), mCallback); 2026 2027 if (mParams.getString(Engine.KEY_PARAM_LANGUAGE) == null) { 2028 String[] defaultLanguage = mService.getClientDefaultLanguage(); 2029 mParams.putString(Engine.KEY_PARAM_LANGUAGE, defaultLanguage[0]); 2030 mParams.putString(Engine.KEY_PARAM_COUNTRY, defaultLanguage[1]); 2031 mParams.putString(Engine.KEY_PARAM_VARIANT, defaultLanguage[2]); 2032 } 2033 2034 Log.i(TAG, "Set up connection to " + mName); 2035 return SUCCESS; 2036 } catch (RemoteException re) { 2037 Log.e(TAG, "Error connecting to service, setCallback() failed"); 2038 return ERROR; 2039 } 2040 } 2041 } 2042 2043 @Override 2044 protected void onPostExecute(Integer result) { 2045 synchronized(mStartLock) { 2046 if (mOnSetupConnectionAsyncTask == this) { 2047 mOnSetupConnectionAsyncTask = null; 2048 } 2049 mEstablished = true; 2050 dispatchOnInit(result); 2051 } 2052 } 2053 } 2054 2055 @Override 2056 public void onServiceConnected(ComponentName name, IBinder service) { 2057 synchronized(mStartLock) { 2058 mConnectingServiceConnection = null; 2059 2060 Log.i(TAG, "Connected to " + name); 2061 2062 if (mOnSetupConnectionAsyncTask != null) { 2063 mOnSetupConnectionAsyncTask.cancel(false); 2064 } 2065 2066 mService = ITextToSpeechService.Stub.asInterface(service); 2067 mServiceConnection = Connection.this; 2068 2069 mEstablished = false; 2070 mOnSetupConnectionAsyncTask = new SetupConnectionAsyncTask(name); 2071 mOnSetupConnectionAsyncTask.execute(); 2072 } 2073 } 2074 2075 public IBinder getCallerIdentity() { 2076 return mCallback; 2077 } 2078 2079 /** 2080 * Clear connection related fields and cancel mOnServiceConnectedAsyncTask if set. 2081 * 2082 * @return true if we cancel mOnSetupConnectionAsyncTask in progress. 2083 */ 2084 private boolean clearServiceConnection() { 2085 synchronized(mStartLock) { 2086 boolean result = false; 2087 if (mOnSetupConnectionAsyncTask != null) { 2088 result = mOnSetupConnectionAsyncTask.cancel(false); 2089 mOnSetupConnectionAsyncTask = null; 2090 } 2091 2092 mService = null; 2093 // If this is the active connection, clear it 2094 if (mServiceConnection == this) { 2095 mServiceConnection = null; 2096 } 2097 return result; 2098 } 2099 } 2100 2101 @Override 2102 public void onServiceDisconnected(ComponentName name) { 2103 Log.i(TAG, "Asked to disconnect from " + name); 2104 if (clearServiceConnection()) { 2105 /* We need to protect against a rare case where engine 2106 * dies just after successful connection - and we process onServiceDisconnected 2107 * before OnServiceConnectedAsyncTask.onPostExecute. onServiceDisconnected cancels 2108 * OnServiceConnectedAsyncTask.onPostExecute and we don't call dispatchOnInit 2109 * with ERROR as argument. 2110 */ 2111 dispatchOnInit(ERROR); 2112 } 2113 } 2114 2115 public void disconnect() { 2116 mContext.unbindService(this); 2117 clearServiceConnection(); 2118 } 2119 2120 public boolean isEstablished() { 2121 return mService != null && mEstablished; 2122 } 2123 2124 public <R> R runAction(Action<R> action, R errorResult, String method, 2125 boolean reconnect, boolean onlyEstablishedConnection) { 2126 synchronized (mStartLock) { 2127 try { 2128 if (mService == null) { 2129 Log.w(TAG, method + " failed: not connected to TTS engine"); 2130 return errorResult; 2131 } 2132 if (onlyEstablishedConnection && !isEstablished()) { 2133 Log.w(TAG, method + " failed: TTS engine connection not fully set up"); 2134 return errorResult; 2135 } 2136 return action.run(mService); 2137 } catch (RemoteException ex) { 2138 Log.e(TAG, method + " failed", ex); 2139 if (reconnect) { 2140 disconnect(); 2141 initTts(); 2142 } 2143 return errorResult; 2144 } 2145 } 2146 } 2147 } 2148 2149 private interface Action<R> { 2150 R run(ITextToSpeechService service) throws RemoteException; 2151 } 2152 2153 /** 2154 * Information about an installed text-to-speech engine. 2155 * 2156 * @see TextToSpeech#getEngines 2157 */ 2158 public static class EngineInfo { 2159 /** 2160 * Engine package name.. 2161 */ 2162 public String name; 2163 /** 2164 * Localized label for the engine. 2165 */ 2166 public String label; 2167 /** 2168 * Icon for the engine. 2169 */ 2170 public int icon; 2171 /** 2172 * Whether this engine is a part of the system 2173 * image. 2174 * 2175 * @hide 2176 */ 2177 public boolean system; 2178 /** 2179 * The priority the engine declares for the the intent filter 2180 * {@code android.intent.action.TTS_SERVICE} 2181 * 2182 * @hide 2183 */ 2184 public int priority; 2185 2186 @Override 2187 public String toString() { 2188 return "EngineInfo{name=" + name + "}"; 2189 } 2190 2191 } 2192 2193 /** 2194 * Limit of length of input string passed to speak and synthesizeToFile. 2195 * 2196 * @see #speak 2197 * @see #synthesizeToFile 2198 */ 2199 public static int getMaxSpeechInputLength() { 2200 return 4000; 2201 } 2202} 2203