TextToSpeech.java revision 228323e759445398e2d723de9365da71099ec58b
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.AudioManager; 26import android.net.Uri; 27import android.os.AsyncTask; 28import android.os.Bundle; 29import android.os.IBinder; 30import android.os.RemoteException; 31import android.provider.Settings; 32import android.text.TextUtils; 33import android.util.Log; 34 35import java.util.Collections; 36import java.util.HashMap; 37import java.util.HashSet; 38import java.util.List; 39import java.util.Locale; 40import java.util.Map; 41import java.util.Set; 42 43/** 44 * 45 * Synthesizes speech from text for immediate playback or to create a sound file. 46 * <p>A TextToSpeech instance can only be used to synthesize text once it has completed its 47 * initialization. Implement the {@link TextToSpeech.OnInitListener} to be 48 * notified of the completion of the initialization.<br> 49 * When you are done using the TextToSpeech instance, call the {@link #shutdown()} method 50 * to release the native resources used by the TextToSpeech engine. 51 * 52 */ 53public class TextToSpeech { 54 55 private static final String TAG = "TextToSpeech"; 56 57 /** 58 * Denotes a successful operation. 59 */ 60 public static final int SUCCESS = 0; 61 /** 62 * Denotes a generic operation failure. 63 */ 64 public static final int ERROR = -1; 65 66 /** 67 * Queue mode where all entries in the playback queue (media to be played 68 * and text to be synthesized) are dropped and replaced by the new entry. 69 * Queues are flushed with respect to a given calling app. Entries in the queue 70 * from other callees are not discarded. 71 */ 72 public static final int QUEUE_FLUSH = 0; 73 /** 74 * Queue mode where the new entry is added at the end of the playback queue. 75 */ 76 public static final int QUEUE_ADD = 1; 77 /** 78 * Queue mode where the entire playback queue is purged. This is different 79 * from {@link #QUEUE_FLUSH} in that all entries are purged, not just entries 80 * from a given caller. 81 * 82 * @hide 83 */ 84 static final int QUEUE_DESTROY = 2; 85 86 /** 87 * Denotes the language is available exactly as specified by the locale. 88 */ 89 public static final int LANG_COUNTRY_VAR_AVAILABLE = 2; 90 91 /** 92 * Denotes the language is available for the language and country specified 93 * by the locale, but not the variant. 94 */ 95 public static final int LANG_COUNTRY_AVAILABLE = 1; 96 97 /** 98 * Denotes the language is available for the language by the locale, 99 * but not the country and variant. 100 */ 101 public static final int LANG_AVAILABLE = 0; 102 103 /** 104 * Denotes the language data is missing. 105 */ 106 public static final int LANG_MISSING_DATA = -1; 107 108 /** 109 * Denotes the language is not supported. 110 */ 111 public static final int LANG_NOT_SUPPORTED = -2; 112 113 /** 114 * Broadcast Action: The TextToSpeech synthesizer has completed processing 115 * of all the text in the speech queue. 116 * 117 * Note that this notifies callers when the <b>engine</b> has finished has 118 * processing text data. Audio playback might not have completed (or even started) 119 * at this point. If you wish to be notified when this happens, see 120 * {@link OnUtteranceCompletedListener}. 121 */ 122 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 123 public static final String ACTION_TTS_QUEUE_PROCESSING_COMPLETED = 124 "android.speech.tts.TTS_QUEUE_PROCESSING_COMPLETED"; 125 126 /** 127 * Interface definition of a callback to be invoked indicating the completion of the 128 * TextToSpeech engine initialization. 129 */ 130 public interface OnInitListener { 131 /** 132 * Called to signal the completion of the TextToSpeech engine initialization. 133 * 134 * @param status {@link TextToSpeech#SUCCESS} or {@link TextToSpeech#ERROR}. 135 */ 136 public void onInit(int status); 137 } 138 139 /** 140 * Listener that will be called when the TTS service has 141 * completed synthesizing an utterance. This is only called if the utterance 142 * has an utterance ID (see {@link TextToSpeech.Engine#KEY_PARAM_UTTERANCE_ID}). 143 */ 144 public interface OnUtteranceCompletedListener { 145 /** 146 * Called when an utterance has been synthesized. 147 * 148 * @param utteranceId the identifier of the utterance. 149 */ 150 public void onUtteranceCompleted(String utteranceId); 151 } 152 153 /** 154 * Constants and parameter names for controlling text-to-speech. These include: 155 * 156 * <ul> 157 * <li> 158 * Intents to ask engine to install data or check its data and 159 * extras for a TTS engine's check data activity. 160 * </li> 161 * <li> 162 * Keys for the parameters passed with speak commands, e.g. 163 * {@link Engine#KEY_PARAM_UTTERANCE_ID}, {@link Engine#KEY_PARAM_STREAM}. 164 * </li> 165 * <li> 166 * A list of feature strings that engines might support, e.g 167 * {@link Engine#KEY_FEATURE_NETWORK_SYNTHESIS}). These values may be passed in to 168 * {@link TextToSpeech#speak} and {@link TextToSpeech#synthesizeToFile} to modify 169 * engine behaviour. The engine can be queried for the set of features it supports 170 * through {@link TextToSpeech#getFeatures(java.util.Locale)}. 171 * </li> 172 * </ul> 173 */ 174 public class Engine { 175 176 /** 177 * Default speech rate. 178 * @hide 179 */ 180 public static final int DEFAULT_RATE = 100; 181 182 /** 183 * Default pitch. 184 * @hide 185 */ 186 public static final int DEFAULT_PITCH = 100; 187 188 /** 189 * Default volume. 190 * @hide 191 */ 192 public static final float DEFAULT_VOLUME = 1.0f; 193 194 /** 195 * Default pan (centered). 196 * @hide 197 */ 198 public static final float DEFAULT_PAN = 0.0f; 199 200 /** 201 * Default value for {@link Settings.Secure#TTS_USE_DEFAULTS}. 202 * @hide 203 */ 204 public static final int USE_DEFAULTS = 0; // false 205 206 /** 207 * Package name of the default TTS engine. 208 * 209 * @hide 210 * @deprecated No longer in use, the default engine is determined by 211 * the sort order defined in {@link TtsEngines}. Note that 212 * this doesn't "break" anything because there is no guarantee that 213 * the engine specified below is installed on a given build, let 214 * alone be the default. 215 */ 216 @Deprecated 217 public static final String DEFAULT_ENGINE = "com.svox.pico"; 218 219 /** 220 * Default audio stream used when playing synthesized speech. 221 */ 222 public static final int DEFAULT_STREAM = AudioManager.STREAM_MUSIC; 223 224 /** 225 * Indicates success when checking the installation status of the resources used by the 226 * TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent. 227 */ 228 public static final int CHECK_VOICE_DATA_PASS = 1; 229 230 /** 231 * Indicates failure when checking the installation status of the resources used by the 232 * TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent. 233 */ 234 public static final int CHECK_VOICE_DATA_FAIL = 0; 235 236 /** 237 * Indicates erroneous data when checking the installation status of the resources used by 238 * the TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent. 239 */ 240 public static final int CHECK_VOICE_DATA_BAD_DATA = -1; 241 242 /** 243 * Indicates missing resources when checking the installation status of the resources used 244 * by the TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent. 245 */ 246 public static final int CHECK_VOICE_DATA_MISSING_DATA = -2; 247 248 /** 249 * Indicates missing storage volume when checking the installation status of the resources 250 * used by the TextToSpeech engine with the {@link #ACTION_CHECK_TTS_DATA} intent. 251 */ 252 public static final int CHECK_VOICE_DATA_MISSING_VOLUME = -3; 253 254 /** 255 * Intent for starting a TTS service. Services that handle this intent must 256 * extend {@link TextToSpeechService}. Normal applications should not use this intent 257 * directly, instead they should talk to the TTS service using the the methods in this 258 * class. 259 */ 260 @SdkConstant(SdkConstantType.SERVICE_ACTION) 261 public static final String INTENT_ACTION_TTS_SERVICE = 262 "android.intent.action.TTS_SERVICE"; 263 264 /** 265 * Name under which a text to speech engine publishes information about itself. 266 * This meta-data should reference an XML resource containing a 267 * <code><{@link android.R.styleable#TextToSpeechEngine tts-engine}></code> 268 * tag. 269 */ 270 public static final String SERVICE_META_DATA = "android.speech.tts"; 271 272 // intents to ask engine to install data or check its data 273 /** 274 * Activity Action: Triggers the platform TextToSpeech engine to 275 * start the activity that installs the resource files on the device 276 * that are required for TTS to be operational. Since the installation 277 * of the data can be interrupted or declined by the user, the application 278 * shouldn't expect successful installation upon return from that intent, 279 * and if need be, should check installation status with 280 * {@link #ACTION_CHECK_TTS_DATA}. 281 */ 282 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 283 public static final String ACTION_INSTALL_TTS_DATA = 284 "android.speech.tts.engine.INSTALL_TTS_DATA"; 285 286 /** 287 * Broadcast Action: broadcast to signal the completion of the installation of 288 * the data files used by the synthesis engine. Success or failure is indicated in the 289 * {@link #EXTRA_TTS_DATA_INSTALLED} extra. 290 */ 291 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 292 public static final String ACTION_TTS_DATA_INSTALLED = 293 "android.speech.tts.engine.TTS_DATA_INSTALLED"; 294 295 /** 296 * Activity Action: Starts the activity from the platform TextToSpeech 297 * engine to verify the proper installation and availability of the 298 * resource files on the system. Upon completion, the activity will 299 * return one of the following codes: 300 * {@link #CHECK_VOICE_DATA_PASS}, 301 * {@link #CHECK_VOICE_DATA_FAIL}, 302 * {@link #CHECK_VOICE_DATA_BAD_DATA}, 303 * {@link #CHECK_VOICE_DATA_MISSING_DATA}, or 304 * {@link #CHECK_VOICE_DATA_MISSING_VOLUME}. 305 * <p> Moreover, the data received in the activity result will contain the following 306 * fields: 307 * <ul> 308 * <li>{@link #EXTRA_VOICE_DATA_ROOT_DIRECTORY} which 309 * indicates the path to the location of the resource files,</li> 310 * <li>{@link #EXTRA_VOICE_DATA_FILES} which contains 311 * the list of all the resource files,</li> 312 * <li>and {@link #EXTRA_VOICE_DATA_FILES_INFO} which 313 * contains, for each resource file, the description of the language covered by 314 * the file in the xxx-YYY format, where xxx is the 3-letter ISO language code, 315 * and YYY is the 3-letter ISO country code.</li> 316 * </ul> 317 */ 318 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 319 public static final String ACTION_CHECK_TTS_DATA = 320 "android.speech.tts.engine.CHECK_TTS_DATA"; 321 322 /** 323 * Activity intent for getting some sample text to use for demonstrating TTS. 324 * 325 * @hide This intent was used by engines written against the old API. 326 * Not sure if it should be exposed. 327 */ 328 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 329 public static final String ACTION_GET_SAMPLE_TEXT = 330 "android.speech.tts.engine.GET_SAMPLE_TEXT"; 331 332 // extras for a TTS engine's check data activity 333 /** 334 * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent where 335 * the TextToSpeech engine specifies the path to its resources. 336 */ 337 public static final String EXTRA_VOICE_DATA_ROOT_DIRECTORY = "dataRoot"; 338 339 /** 340 * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent where 341 * the TextToSpeech engine specifies the file names of its resources under the 342 * resource path. 343 */ 344 public static final String EXTRA_VOICE_DATA_FILES = "dataFiles"; 345 346 /** 347 * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent where 348 * the TextToSpeech engine specifies the locale associated with each resource file. 349 */ 350 public static final String EXTRA_VOICE_DATA_FILES_INFO = "dataFilesInfo"; 351 352 /** 353 * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent where 354 * the TextToSpeech engine returns an ArrayList<String> of all the available voices. 355 * The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are 356 * optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). 357 */ 358 public static final String EXTRA_AVAILABLE_VOICES = "availableVoices"; 359 360 /** 361 * Extra information received with the {@link #ACTION_CHECK_TTS_DATA} intent where 362 * the TextToSpeech engine returns an ArrayList<String> of all the unavailable voices. 363 * The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are 364 * optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). 365 */ 366 public static final String EXTRA_UNAVAILABLE_VOICES = "unavailableVoices"; 367 368 /** 369 * Extra information sent with the {@link #ACTION_CHECK_TTS_DATA} intent where the 370 * caller indicates to the TextToSpeech engine which specific sets of voice data to 371 * check for by sending an ArrayList<String> of the voices that are of interest. 372 * The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are 373 * optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). 374 */ 375 public static final String EXTRA_CHECK_VOICE_DATA_FOR = "checkVoiceDataFor"; 376 377 // extras for a TTS engine's data installation 378 /** 379 * Extra information received with the {@link #ACTION_TTS_DATA_INSTALLED} intent. 380 * It indicates whether the data files for the synthesis engine were successfully 381 * installed. The installation was initiated with the {@link #ACTION_INSTALL_TTS_DATA} 382 * intent. The possible values for this extra are 383 * {@link TextToSpeech#SUCCESS} and {@link TextToSpeech#ERROR}. 384 */ 385 public static final String EXTRA_TTS_DATA_INSTALLED = "dataInstalled"; 386 387 // keys for the parameters passed with speak commands. Hidden keys are used internally 388 // to maintain engine state for each TextToSpeech instance. 389 /** 390 * @hide 391 */ 392 public static final String KEY_PARAM_RATE = "rate"; 393 394 /** 395 * @hide 396 */ 397 public static final String KEY_PARAM_LANGUAGE = "language"; 398 399 /** 400 * @hide 401 */ 402 public static final String KEY_PARAM_COUNTRY = "country"; 403 404 /** 405 * @hide 406 */ 407 public static final String KEY_PARAM_VARIANT = "variant"; 408 409 /** 410 * @hide 411 */ 412 public static final String KEY_PARAM_ENGINE = "engine"; 413 414 /** 415 * @hide 416 */ 417 public static final String KEY_PARAM_PITCH = "pitch"; 418 419 /** 420 * Parameter key to specify the audio stream type to be used when speaking text 421 * or playing back a file. The value should be one of the STREAM_ constants 422 * defined in {@link AudioManager}. 423 * 424 * @see TextToSpeech#speak(String, int, HashMap) 425 * @see TextToSpeech#playEarcon(String, int, HashMap) 426 */ 427 public static final String KEY_PARAM_STREAM = "streamType"; 428 429 /** 430 * Parameter key to identify an utterance in the 431 * {@link TextToSpeech.OnUtteranceCompletedListener} after text has been 432 * spoken, a file has been played back or a silence duration has elapsed. 433 * 434 * @see TextToSpeech#speak(String, int, HashMap) 435 * @see TextToSpeech#playEarcon(String, int, HashMap) 436 * @see TextToSpeech#synthesizeToFile(String, HashMap, String) 437 */ 438 public static final String KEY_PARAM_UTTERANCE_ID = "utteranceId"; 439 440 /** 441 * Parameter key to specify the speech volume relative to the current stream type 442 * volume used when speaking text. Volume is specified as a float ranging from 0 to 1 443 * where 0 is silence, and 1 is the maximum volume (the default behavior). 444 * 445 * @see TextToSpeech#speak(String, int, HashMap) 446 * @see TextToSpeech#playEarcon(String, int, HashMap) 447 */ 448 public static final String KEY_PARAM_VOLUME = "volume"; 449 450 /** 451 * Parameter key to specify how the speech is panned from left to right when speaking text. 452 * Pan is specified as a float ranging from -1 to +1 where -1 maps to a hard-left pan, 453 * 0 to center (the default behavior), and +1 to hard-right. 454 * 455 * @see TextToSpeech#speak(String, int, HashMap) 456 * @see TextToSpeech#playEarcon(String, int, HashMap) 457 */ 458 public static final String KEY_PARAM_PAN = "pan"; 459 460 /** 461 * Feature key for network synthesis. See {@link TextToSpeech#getFeatures(Locale)} 462 * for a description of how feature keys work. If set (and supported by the engine 463 * as per {@link TextToSpeech#getFeatures(Locale)}, the engine must 464 * use network based synthesis. 465 * 466 * @see TextToSpeech#speak(String, int, java.util.HashMap) 467 * @see TextToSpeech#synthesizeToFile(String, java.util.HashMap, String) 468 * @see TextToSpeech#getFeatures(java.util.Locale) 469 */ 470 public static final String KEY_FEATURE_NETWORK_SYNTHESIS = "networkTts"; 471 472 /** 473 * Feature key for embedded synthesis. See {@link TextToSpeech#getFeatures(Locale)} 474 * for a description of how feature keys work. If set and supported by the engine 475 * as per {@link TextToSpeech#getFeatures(Locale)}, the engine must synthesize 476 * text on-device (without making network requests). 477 */ 478 public static final String KEY_FEATURE_EMBEDDED_SYNTHESIS = "embeddedTts"; 479 } 480 481 private final Context mContext; 482 private Connection mServiceConnection; 483 private OnInitListener mInitListener; 484 // Written from an unspecified application thread, read from 485 // a binder thread. 486 private volatile UtteranceProgressListener mUtteranceProgressListener; 487 private final Object mStartLock = new Object(); 488 489 private String mRequestedEngine; 490 // Whether to initialize this TTS object with the default engine, 491 // if the requested engine is not available. Valid only if mRequestedEngine 492 // is not null. Used only for testing, though potentially useful API wise 493 // too. 494 private final boolean mUseFallback; 495 private final Map<String, Uri> mEarcons; 496 private final Map<String, Uri> mUtterances; 497 private final Bundle mParams = new Bundle(); 498 private final TtsEngines mEnginesHelper; 499 private final String mPackageName; 500 private volatile String mCurrentEngine = null; 501 502 /** 503 * The constructor for the TextToSpeech class, using the default TTS engine. 504 * This will also initialize the associated TextToSpeech engine if it isn't already running. 505 * 506 * @param context 507 * The context this instance is running in. 508 * @param listener 509 * The {@link TextToSpeech.OnInitListener} that will be called when the 510 * TextToSpeech engine has initialized. 511 */ 512 public TextToSpeech(Context context, OnInitListener listener) { 513 this(context, listener, null); 514 } 515 516 /** 517 * The constructor for the TextToSpeech class, using the given TTS engine. 518 * This will also initialize the associated TextToSpeech engine if it isn't already running. 519 * 520 * @param context 521 * The context this instance is running in. 522 * @param listener 523 * The {@link TextToSpeech.OnInitListener} that will be called when the 524 * TextToSpeech engine has initialized. 525 * @param engine Package name of the TTS engine to use. 526 */ 527 public TextToSpeech(Context context, OnInitListener listener, String engine) { 528 this(context, listener, engine, null, true); 529 } 530 531 /** 532 * Used by the framework to instantiate TextToSpeech objects with a supplied 533 * package name, instead of using {@link android.content.Context#getPackageName()} 534 * 535 * @hide 536 */ 537 public TextToSpeech(Context context, OnInitListener listener, String engine, 538 String packageName, boolean useFallback) { 539 mContext = context; 540 mInitListener = listener; 541 mRequestedEngine = engine; 542 mUseFallback = useFallback; 543 544 mEarcons = new HashMap<String, Uri>(); 545 mUtterances = new HashMap<String, Uri>(); 546 mUtteranceProgressListener = null; 547 548 mEnginesHelper = new TtsEngines(mContext); 549 if (packageName != null) { 550 mPackageName = packageName; 551 } else { 552 mPackageName = mContext.getPackageName(); 553 } 554 initTts(); 555 } 556 557 private <R> R runActionNoReconnect(Action<R> action, R errorResult, String method) { 558 return runAction(action, errorResult, method, false); 559 } 560 561 private <R> R runAction(Action<R> action, R errorResult, String method) { 562 return runAction(action, errorResult, method, true); 563 } 564 565 private <R> R runAction(Action<R> action, R errorResult, String method, boolean reconnect) { 566 synchronized (mStartLock) { 567 if (mServiceConnection == null) { 568 Log.w(TAG, method + " failed: not bound to TTS engine"); 569 return errorResult; 570 } 571 return mServiceConnection.runAction(action, errorResult, method, reconnect); 572 } 573 } 574 575 private int initTts() { 576 // Step 1: Try connecting to the engine that was requested. 577 if (mRequestedEngine != null) { 578 if (mEnginesHelper.isEngineInstalled(mRequestedEngine)) { 579 if (connectToEngine(mRequestedEngine)) { 580 mCurrentEngine = mRequestedEngine; 581 return SUCCESS; 582 } else if (!mUseFallback) { 583 mCurrentEngine = null; 584 dispatchOnInit(ERROR); 585 return ERROR; 586 } 587 } else if (!mUseFallback) { 588 Log.i(TAG, "Requested engine not installed: " + mRequestedEngine); 589 mCurrentEngine = null; 590 dispatchOnInit(ERROR); 591 return ERROR; 592 } 593 } 594 595 // Step 2: Try connecting to the user's default engine. 596 final String defaultEngine = getDefaultEngine(); 597 if (defaultEngine != null && !defaultEngine.equals(mRequestedEngine)) { 598 if (connectToEngine(defaultEngine)) { 599 mCurrentEngine = defaultEngine; 600 return SUCCESS; 601 } 602 } 603 604 // Step 3: Try connecting to the highest ranked engine in the 605 // system. 606 final String highestRanked = mEnginesHelper.getHighestRankedEngineName(); 607 if (highestRanked != null && !highestRanked.equals(mRequestedEngine) && 608 !highestRanked.equals(defaultEngine)) { 609 if (connectToEngine(highestRanked)) { 610 mCurrentEngine = highestRanked; 611 return SUCCESS; 612 } 613 } 614 615 // NOTE: The API currently does not allow the caller to query whether 616 // they are actually connected to any engine. This might fail for various 617 // reasons like if the user disables all her TTS engines. 618 619 mCurrentEngine = null; 620 dispatchOnInit(ERROR); 621 return ERROR; 622 } 623 624 private boolean connectToEngine(String engine) { 625 Connection connection = new Connection(); 626 Intent intent = new Intent(Engine.INTENT_ACTION_TTS_SERVICE); 627 intent.setPackage(engine); 628 boolean bound = mContext.bindService(intent, connection, Context.BIND_AUTO_CREATE); 629 if (!bound) { 630 Log.e(TAG, "Failed to bind to " + engine); 631 return false; 632 } else { 633 Log.i(TAG, "Sucessfully bound to " + engine); 634 return true; 635 } 636 } 637 638 private void dispatchOnInit(int result) { 639 synchronized (mStartLock) { 640 if (mInitListener != null) { 641 mInitListener.onInit(result); 642 mInitListener = null; 643 } 644 } 645 } 646 647 private IBinder getCallerIdentity() { 648 return mServiceConnection.getCallerIdentity(); 649 } 650 651 /** 652 * Releases the resources used by the TextToSpeech engine. 653 * It is good practice for instance to call this method in the onDestroy() method of an Activity 654 * so the TextToSpeech engine can be cleanly stopped. 655 */ 656 public void shutdown() { 657 runActionNoReconnect(new Action<Void>() { 658 @Override 659 public Void run(ITextToSpeechService service) throws RemoteException { 660 service.setCallback(getCallerIdentity(), null); 661 service.stop(getCallerIdentity()); 662 mServiceConnection.disconnect(); 663 // Context#unbindService does not result in a call to 664 // ServiceConnection#onServiceDisconnected. As a result, the 665 // service ends up being destroyed (if there are no other open 666 // connections to it) but the process lives on and the 667 // ServiceConnection continues to refer to the destroyed service. 668 // 669 // This leads to tons of log spam about SynthThread being dead. 670 mServiceConnection = null; 671 mCurrentEngine = null; 672 return null; 673 } 674 }, null, "shutdown"); 675 } 676 677 /** 678 * Adds a mapping between a string of text and a sound resource in a 679 * package. After a call to this method, subsequent calls to 680 * {@link #speak(String, int, HashMap)} will play the specified sound resource 681 * if it is available, or synthesize the text it is missing. 682 * 683 * @param text 684 * The string of text. Example: <code>"south_south_east"</code> 685 * 686 * @param packagename 687 * Pass the packagename of the application that contains the 688 * resource. If the resource is in your own application (this is 689 * the most common case), then put the packagename of your 690 * application here.<br/> 691 * Example: <b>"com.google.marvin.compass"</b><br/> 692 * The packagename can be found in the AndroidManifest.xml of 693 * your application. 694 * <p> 695 * <code><manifest xmlns:android="..." 696 * package="<b>com.google.marvin.compass</b>"></code> 697 * </p> 698 * 699 * @param resourceId 700 * Example: <code>R.raw.south_south_east</code> 701 * 702 * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 703 */ 704 public int addSpeech(String text, String packagename, int resourceId) { 705 synchronized (mStartLock) { 706 mUtterances.put(text, makeResourceUri(packagename, resourceId)); 707 return SUCCESS; 708 } 709 } 710 711 /** 712 * Adds a mapping between a string of text and a sound file. Using this, it 713 * is possible to add custom pronounciations for a string of text. 714 * After a call to this method, subsequent calls to {@link #speak(String, int, HashMap)} 715 * will play the specified sound resource if it is available, or synthesize the text it is 716 * missing. 717 * 718 * @param text 719 * The string of text. Example: <code>"south_south_east"</code> 720 * @param filename 721 * The full path to the sound file (for example: 722 * "/sdcard/mysounds/hello.wav") 723 * 724 * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 725 */ 726 public int addSpeech(String text, String filename) { 727 synchronized (mStartLock) { 728 mUtterances.put(text, Uri.parse(filename)); 729 return SUCCESS; 730 } 731 } 732 733 734 /** 735 * Adds a mapping between a string of text and a sound resource in a 736 * package. Use this to add custom earcons. 737 * 738 * @see #playEarcon(String, int, HashMap) 739 * 740 * @param earcon The name of the earcon. 741 * Example: <code>"[tick]"</code><br/> 742 * 743 * @param packagename 744 * the package name of the application that contains the 745 * resource. This can for instance be the package name of your own application. 746 * Example: <b>"com.google.marvin.compass"</b><br/> 747 * The package name can be found in the AndroidManifest.xml of 748 * the application containing the resource. 749 * <p> 750 * <code><manifest xmlns:android="..." 751 * package="<b>com.google.marvin.compass</b>"></code> 752 * </p> 753 * 754 * @param resourceId 755 * Example: <code>R.raw.tick_snd</code> 756 * 757 * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 758 */ 759 public int addEarcon(String earcon, String packagename, int resourceId) { 760 synchronized(mStartLock) { 761 mEarcons.put(earcon, makeResourceUri(packagename, resourceId)); 762 return SUCCESS; 763 } 764 } 765 766 /** 767 * Adds a mapping between a string of text and a sound file. 768 * Use this to add custom earcons. 769 * 770 * @see #playEarcon(String, int, HashMap) 771 * 772 * @param earcon 773 * The name of the earcon. 774 * Example: <code>"[tick]"</code> 775 * @param filename 776 * The full path to the sound file (for example: 777 * "/sdcard/mysounds/tick.wav") 778 * 779 * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 780 */ 781 public int addEarcon(String earcon, String filename) { 782 synchronized(mStartLock) { 783 mEarcons.put(earcon, Uri.parse(filename)); 784 return SUCCESS; 785 } 786 } 787 788 private Uri makeResourceUri(String packageName, int resourceId) { 789 return new Uri.Builder() 790 .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) 791 .encodedAuthority(packageName) 792 .appendEncodedPath(String.valueOf(resourceId)) 793 .build(); 794 } 795 796 /** 797 * Speaks the string using the specified queuing strategy and speech parameters. 798 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 799 * requests and then returns. The synthesis might not have finished (or even started!) at the 800 * time when this method returns. In order to reliably detect errors during synthesis, 801 * we recommend setting an utterance progress listener (see 802 * {@link #setOnUtteranceProgressListener}) and using the 803 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 804 * 805 * @param text The string of text to be spoken. 806 * @param queueMode The queuing strategy to use, {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 807 * @param params Parameters for the request. Can be null. 808 * Supported parameter names: 809 * {@link Engine#KEY_PARAM_STREAM}, 810 * {@link Engine#KEY_PARAM_UTTERANCE_ID}, 811 * {@link Engine#KEY_PARAM_VOLUME}, 812 * {@link Engine#KEY_PARAM_PAN}. 813 * Engine specific parameters may be passed in but the parameter keys 814 * must be prefixed by the name of the engine they are intended for. For example 815 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 816 * engine named "com.svox.pico" if it is being used. 817 * 818 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the speak operation. 819 */ 820 public int speak(final String text, final int queueMode, final HashMap<String, String> params) { 821 return runAction(new Action<Integer>() { 822 @Override 823 public Integer run(ITextToSpeechService service) throws RemoteException { 824 Uri utteranceUri = mUtterances.get(text); 825 if (utteranceUri != null) { 826 return service.playAudio(getCallerIdentity(), utteranceUri, queueMode, 827 getParams(params)); 828 } else { 829 return service.speak(getCallerIdentity(), text, queueMode, getParams(params)); 830 } 831 } 832 }, ERROR, "speak"); 833 } 834 835 /** 836 * Plays the earcon using the specified queueing mode and parameters. 837 * The earcon must already have been added with {@link #addEarcon(String, String)} or 838 * {@link #addEarcon(String, String, int)}. 839 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 840 * requests and then returns. The synthesis might not have finished (or even started!) at the 841 * time when this method returns. In order to reliably detect errors during synthesis, 842 * we recommend setting an utterance progress listener (see 843 * {@link #setOnUtteranceProgressListener}) and using the 844 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 845 * 846 * @param earcon The earcon that should be played 847 * @param queueMode {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 848 * @param params Parameters for the request. Can be null. 849 * Supported parameter names: 850 * {@link Engine#KEY_PARAM_STREAM}, 851 * {@link Engine#KEY_PARAM_UTTERANCE_ID}. 852 * Engine specific parameters may be passed in but the parameter keys 853 * must be prefixed by the name of the engine they are intended for. For example 854 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 855 * engine named "com.svox.pico" if it is being used. 856 * 857 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the playEarcon operation. 858 */ 859 public int playEarcon(final String earcon, final int queueMode, 860 final HashMap<String, String> params) { 861 return runAction(new Action<Integer>() { 862 @Override 863 public Integer run(ITextToSpeechService service) throws RemoteException { 864 Uri earconUri = mEarcons.get(earcon); 865 if (earconUri == null) { 866 return ERROR; 867 } 868 return service.playAudio(getCallerIdentity(), earconUri, queueMode, 869 getParams(params)); 870 } 871 }, ERROR, "playEarcon"); 872 } 873 874 /** 875 * Plays silence for the specified amount of time using the specified 876 * queue mode. 877 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 878 * requests and then returns. The synthesis might not have finished (or even started!) at the 879 * time when this method returns. In order to reliably detect errors during synthesis, 880 * we recommend setting an utterance progress listener (see 881 * {@link #setOnUtteranceProgressListener}) and using the 882 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 883 * 884 * @param durationInMs The duration of the silence. 885 * @param queueMode {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 886 * @param params Parameters for the request. Can be null. 887 * Supported parameter names: 888 * {@link Engine#KEY_PARAM_UTTERANCE_ID}. 889 * Engine specific parameters may be passed in but the parameter keys 890 * must be prefixed by the name of the engine they are intended for. For example 891 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 892 * engine named "com.svox.pico" if it is being used. 893 * 894 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the playSilence operation. 895 */ 896 public int playSilence(final long durationInMs, final int queueMode, 897 final HashMap<String, String> params) { 898 return runAction(new Action<Integer>() { 899 @Override 900 public Integer run(ITextToSpeechService service) throws RemoteException { 901 return service.playSilence(getCallerIdentity(), durationInMs, queueMode, 902 getParams(params)); 903 } 904 }, ERROR, "playSilence"); 905 } 906 907 /** 908 * Queries the engine for the set of features it supports for a given locale. 909 * Features can either be framework defined, e.g. 910 * {@link TextToSpeech.Engine#KEY_FEATURE_NETWORK_SYNTHESIS} or engine specific. 911 * Engine specific keys must be prefixed by the name of the engine they 912 * are intended for. These keys can be used as parameters to 913 * {@link TextToSpeech#speak(String, int, java.util.HashMap)} and 914 * {@link TextToSpeech#synthesizeToFile(String, java.util.HashMap, String)}. 915 * 916 * Features are boolean flags, and their values in the synthesis parameters 917 * must be behave as per {@link Boolean#parseBoolean(String)}. 918 * 919 * @param locale The locale to query features for. 920 */ 921 public Set<String> getFeatures(final Locale locale) { 922 return runAction(new Action<Set<String>>() { 923 @Override 924 public Set<String> run(ITextToSpeechService service) throws RemoteException { 925 String[] features = service.getFeaturesForLanguage( 926 locale.getISO3Language(), locale.getISO3Country(), locale.getVariant()); 927 if (features != null) { 928 final Set<String> featureSet = new HashSet<String>(); 929 Collections.addAll(featureSet, features); 930 return featureSet; 931 } 932 return null; 933 } 934 }, null, "getFeatures"); 935 } 936 937 /** 938 * Checks whether the TTS engine is busy speaking. Note that a speech item is 939 * considered complete once it's audio data has been sent to the audio mixer, or 940 * written to a file. There might be a finite lag between this point, and when 941 * the audio hardware completes playback. 942 * 943 * @return {@code true} if the TTS engine is speaking. 944 */ 945 public boolean isSpeaking() { 946 return runAction(new Action<Boolean>() { 947 @Override 948 public Boolean run(ITextToSpeechService service) throws RemoteException { 949 return service.isSpeaking(); 950 } 951 }, false, "isSpeaking"); 952 } 953 954 /** 955 * Interrupts the current utterance (whether played or rendered to file) and discards other 956 * utterances in the queue. 957 * 958 * @return {@link #ERROR} or {@link #SUCCESS}. 959 */ 960 public int stop() { 961 return runAction(new Action<Integer>() { 962 @Override 963 public Integer run(ITextToSpeechService service) throws RemoteException { 964 return service.stop(getCallerIdentity()); 965 } 966 }, ERROR, "stop"); 967 } 968 969 /** 970 * Sets the speech rate. 971 * 972 * This has no effect on any pre-recorded speech. 973 * 974 * @param speechRate Speech rate. {@code 1.0} is the normal speech rate, 975 * lower values slow down the speech ({@code 0.5} is half the normal speech rate), 976 * greater values accelerate it ({@code 2.0} is twice the normal speech rate). 977 * 978 * @return {@link #ERROR} or {@link #SUCCESS}. 979 */ 980 public int setSpeechRate(float speechRate) { 981 if (speechRate > 0.0f) { 982 int intRate = (int)(speechRate * 100); 983 if (intRate > 0) { 984 synchronized (mStartLock) { 985 mParams.putInt(Engine.KEY_PARAM_RATE, intRate); 986 } 987 return SUCCESS; 988 } 989 } 990 return ERROR; 991 } 992 993 /** 994 * Sets the speech pitch for the TextToSpeech engine. 995 * 996 * This has no effect on any pre-recorded speech. 997 * 998 * @param pitch Speech pitch. {@code 1.0} is the normal pitch, 999 * lower values lower the tone of the synthesized voice, 1000 * greater values increase it. 1001 * 1002 * @return {@link #ERROR} or {@link #SUCCESS}. 1003 */ 1004 public int setPitch(float pitch) { 1005 if (pitch > 0.0f) { 1006 int intPitch = (int)(pitch * 100); 1007 if (intPitch > 0) { 1008 synchronized (mStartLock) { 1009 mParams.putInt(Engine.KEY_PARAM_PITCH, intPitch); 1010 } 1011 return SUCCESS; 1012 } 1013 } 1014 return ERROR; 1015 } 1016 1017 /** 1018 * @return the engine currently in use by this TextToSpeech instance. 1019 * @hide 1020 */ 1021 public String getCurrentEngine() { 1022 return mCurrentEngine; 1023 } 1024 1025 /** 1026 * Sets the text-to-speech language. 1027 * The TTS engine will try to use the closest match to the specified 1028 * language as represented by the Locale, but there is no guarantee that the exact same Locale 1029 * will be used. Use {@link #isLanguageAvailable(Locale)} to check the level of support 1030 * before choosing the language to use for the next utterances. 1031 * 1032 * @param loc The locale describing the language to be used. 1033 * 1034 * @return Code indicating the support status for the locale. See {@link #LANG_AVAILABLE}, 1035 * {@link #LANG_COUNTRY_AVAILABLE}, {@link #LANG_COUNTRY_VAR_AVAILABLE}, 1036 * {@link #LANG_MISSING_DATA} and {@link #LANG_NOT_SUPPORTED}. 1037 */ 1038 public int setLanguage(final Locale loc) { 1039 return runAction(new Action<Integer>() { 1040 @Override 1041 public Integer run(ITextToSpeechService service) throws RemoteException { 1042 if (loc == null) { 1043 return LANG_NOT_SUPPORTED; 1044 } 1045 String language = loc.getISO3Language(); 1046 String country = loc.getISO3Country(); 1047 String variant = loc.getVariant(); 1048 // Check if the language, country, variant are available, and cache 1049 // the available parts. 1050 // Note that the language is not actually set here, instead it is cached so it 1051 // will be associated with all upcoming utterances. 1052 int result = service.loadLanguage(language, country, variant); 1053 if (result >= LANG_AVAILABLE){ 1054 if (result < LANG_COUNTRY_VAR_AVAILABLE) { 1055 variant = ""; 1056 if (result < LANG_COUNTRY_AVAILABLE) { 1057 country = ""; 1058 } 1059 } 1060 mParams.putString(Engine.KEY_PARAM_LANGUAGE, language); 1061 mParams.putString(Engine.KEY_PARAM_COUNTRY, country); 1062 mParams.putString(Engine.KEY_PARAM_VARIANT, variant); 1063 } 1064 return result; 1065 } 1066 }, LANG_NOT_SUPPORTED, "setLanguage"); 1067 } 1068 1069 /** 1070 * Returns a Locale instance describing the language currently being used for synthesis 1071 * requests sent to the TextToSpeech engine. 1072 * 1073 * In Android 4.2 and before (API <= 17) this function returns the language that is currently 1074 * being used by the TTS engine. That is the last language set by this or any other 1075 * client by a {@link TextToSpeech#setLanguage} call to the same engine. 1076 * 1077 * In Android versions after 4.2 this function returns the language that is currently being 1078 * used for the synthesis requests sent from this client. That is the last language set 1079 * by a {@link TextToSpeech#setLanguage} call on this instance. 1080 * 1081 * @return language, country (if any) and variant (if any) used by the client stored in a 1082 * Locale instance, or {@code null} on error. 1083 */ 1084 public Locale getLanguage() { 1085 return runAction(new Action<Locale>() { 1086 @Override 1087 public Locale run(ITextToSpeechService service) { 1088 /* No service call, but we're accessing mParams, hence need for 1089 wrapping it as an Action instance */ 1090 String lang = mParams.getString(Engine.KEY_PARAM_LANGUAGE, ""); 1091 String country = mParams.getString(Engine.KEY_PARAM_COUNTRY, ""); 1092 String variant = mParams.getString(Engine.KEY_PARAM_VARIANT, ""); 1093 return new Locale(lang, country, variant); 1094 } 1095 }, null, "getLanguage"); 1096 } 1097 1098 /** 1099 * Checks if the specified language as represented by the Locale is available and supported. 1100 * 1101 * @param loc The Locale describing the language to be used. 1102 * 1103 * @return Code indicating the support status for the locale. See {@link #LANG_AVAILABLE}, 1104 * {@link #LANG_COUNTRY_AVAILABLE}, {@link #LANG_COUNTRY_VAR_AVAILABLE}, 1105 * {@link #LANG_MISSING_DATA} and {@link #LANG_NOT_SUPPORTED}. 1106 */ 1107 public int isLanguageAvailable(final Locale loc) { 1108 return runAction(new Action<Integer>() { 1109 @Override 1110 public Integer run(ITextToSpeechService service) throws RemoteException { 1111 return service.isLanguageAvailable(loc.getISO3Language(), 1112 loc.getISO3Country(), loc.getVariant()); 1113 } 1114 }, LANG_NOT_SUPPORTED, "isLanguageAvailable"); 1115 } 1116 1117 /** 1118 * Synthesizes the given text to a file using the specified parameters. 1119 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 1120 * requests and then returns. The synthesis might not have finished (or even started!) at the 1121 * time when this method returns. In order to reliably detect errors during synthesis, 1122 * we recommend setting an utterance progress listener (see 1123 * {@link #setOnUtteranceProgressListener}) and using the 1124 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 1125 * 1126 * @param text The text that should be synthesized 1127 * @param params Parameters for the request. Can be null. 1128 * Supported parameter names: 1129 * {@link Engine#KEY_PARAM_UTTERANCE_ID}. 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 * @param filename Absolute file filename to write the generated audio data to.It should be 1135 * something like "/sdcard/myappsounds/mysound.wav". 1136 * 1137 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the synthesizeToFile operation. 1138 */ 1139 public int synthesizeToFile(final String text, final HashMap<String, String> params, 1140 final String filename) { 1141 return runAction(new Action<Integer>() { 1142 @Override 1143 public Integer run(ITextToSpeechService service) throws RemoteException { 1144 return service.synthesizeToFile(getCallerIdentity(), text, filename, 1145 getParams(params)); 1146 } 1147 }, ERROR, "synthesizeToFile"); 1148 } 1149 1150 private Bundle getParams(HashMap<String, String> params) { 1151 if (params != null && !params.isEmpty()) { 1152 Bundle bundle = new Bundle(mParams); 1153 copyIntParam(bundle, params, Engine.KEY_PARAM_STREAM); 1154 copyStringParam(bundle, params, Engine.KEY_PARAM_UTTERANCE_ID); 1155 copyFloatParam(bundle, params, Engine.KEY_PARAM_VOLUME); 1156 copyFloatParam(bundle, params, Engine.KEY_PARAM_PAN); 1157 1158 // Copy feature strings defined by the framework. 1159 copyStringParam(bundle, params, Engine.KEY_FEATURE_NETWORK_SYNTHESIS); 1160 copyStringParam(bundle, params, Engine.KEY_FEATURE_EMBEDDED_SYNTHESIS); 1161 1162 // Copy over all parameters that start with the name of the 1163 // engine that we are currently connected to. The engine is 1164 // free to interpret them as it chooses. 1165 if (!TextUtils.isEmpty(mCurrentEngine)) { 1166 for (Map.Entry<String, String> entry : params.entrySet()) { 1167 final String key = entry.getKey(); 1168 if (key != null && key.startsWith(mCurrentEngine)) { 1169 bundle.putString(key, entry.getValue()); 1170 } 1171 } 1172 } 1173 1174 return bundle; 1175 } else { 1176 return mParams; 1177 } 1178 } 1179 1180 private void copyStringParam(Bundle bundle, HashMap<String, String> params, String key) { 1181 String value = params.get(key); 1182 if (value != null) { 1183 bundle.putString(key, value); 1184 } 1185 } 1186 1187 private void copyIntParam(Bundle bundle, HashMap<String, String> params, String key) { 1188 String valueString = params.get(key); 1189 if (!TextUtils.isEmpty(valueString)) { 1190 try { 1191 int value = Integer.parseInt(valueString); 1192 bundle.putInt(key, value); 1193 } catch (NumberFormatException ex) { 1194 // don't set the value in the bundle 1195 } 1196 } 1197 } 1198 1199 private void copyFloatParam(Bundle bundle, HashMap<String, String> params, String key) { 1200 String valueString = params.get(key); 1201 if (!TextUtils.isEmpty(valueString)) { 1202 try { 1203 float value = Float.parseFloat(valueString); 1204 bundle.putFloat(key, value); 1205 } catch (NumberFormatException ex) { 1206 // don't set the value in the bundle 1207 } 1208 } 1209 } 1210 1211 /** 1212 * Sets the listener that will be notified when synthesis of an utterance completes. 1213 * 1214 * @param listener The listener to use. 1215 * 1216 * @return {@link #ERROR} or {@link #SUCCESS}. 1217 * 1218 * @deprecated Use {@link #setOnUtteranceProgressListener(UtteranceProgressListener)} 1219 * instead. 1220 */ 1221 @Deprecated 1222 public int setOnUtteranceCompletedListener(final OnUtteranceCompletedListener listener) { 1223 mUtteranceProgressListener = UtteranceProgressListener.from(listener); 1224 return TextToSpeech.SUCCESS; 1225 } 1226 1227 /** 1228 * Sets the listener that will be notified of various events related to the 1229 * synthesis of a given utterance. 1230 * 1231 * See {@link UtteranceProgressListener} and 1232 * {@link TextToSpeech.Engine#KEY_PARAM_UTTERANCE_ID}. 1233 * 1234 * @param listener the listener to use. 1235 * @return {@link #ERROR} or {@link #SUCCESS} 1236 */ 1237 public int setOnUtteranceProgressListener(UtteranceProgressListener listener) { 1238 mUtteranceProgressListener = listener; 1239 return TextToSpeech.SUCCESS; 1240 } 1241 1242 /** 1243 * Sets the TTS engine to use. 1244 * 1245 * @deprecated This doesn't inform callers when the TTS engine has been 1246 * initialized. {@link #TextToSpeech(Context, OnInitListener, String)} 1247 * can be used with the appropriate engine name. Also, there is no 1248 * guarantee that the engine specified will be loaded. If it isn't 1249 * installed or disabled, the user / system wide defaults will apply. 1250 * 1251 * @param enginePackageName The package name for the synthesis engine (e.g. "com.svox.pico") 1252 * 1253 * @return {@link #ERROR} or {@link #SUCCESS}. 1254 */ 1255 @Deprecated 1256 public int setEngineByPackageName(String enginePackageName) { 1257 mRequestedEngine = enginePackageName; 1258 return initTts(); 1259 } 1260 1261 /** 1262 * Gets the package name of the default speech synthesis engine. 1263 * 1264 * @return Package name of the TTS engine that the user has chosen 1265 * as their default. 1266 */ 1267 public String getDefaultEngine() { 1268 return mEnginesHelper.getDefaultEngine(); 1269 } 1270 1271 /** 1272 * Checks whether the user's settings should override settings requested 1273 * by the calling application. As of the Ice cream sandwich release, 1274 * user settings never forcibly override the app's settings. 1275 */ 1276 public boolean areDefaultsEnforced() { 1277 return false; 1278 } 1279 1280 /** 1281 * Gets a list of all installed TTS engines. 1282 * 1283 * @return A list of engine info objects. The list can be empty, but never {@code null}. 1284 */ 1285 public List<EngineInfo> getEngines() { 1286 return mEnginesHelper.getEngines(); 1287 } 1288 1289 private class Connection implements ServiceConnection { 1290 private ITextToSpeechService mService; 1291 1292 private OnServiceConnectedAsyncTask mOnServiceConnectedAsyncTask; 1293 1294 private final ITextToSpeechCallback.Stub mCallback = new ITextToSpeechCallback.Stub() { 1295 @Override 1296 public void onDone(String utteranceId) { 1297 UtteranceProgressListener listener = mUtteranceProgressListener; 1298 if (listener != null) { 1299 listener.onDone(utteranceId); 1300 } 1301 } 1302 1303 @Override 1304 public void onError(String utteranceId) { 1305 UtteranceProgressListener listener = mUtteranceProgressListener; 1306 if (listener != null) { 1307 listener.onError(utteranceId); 1308 } 1309 } 1310 1311 @Override 1312 public void onStart(String utteranceId) { 1313 UtteranceProgressListener listener = mUtteranceProgressListener; 1314 if (listener != null) { 1315 listener.onStart(utteranceId); 1316 } 1317 } 1318 }; 1319 1320 private class OnServiceConnectedAsyncTask extends AsyncTask<Void, Void, Integer> { 1321 private final ComponentName mName; 1322 private final ITextToSpeechService mConnectedService; 1323 1324 public OnServiceConnectedAsyncTask(ComponentName name, IBinder service) { 1325 mName = name; 1326 mConnectedService = ITextToSpeechService.Stub.asInterface(service); 1327 } 1328 1329 @Override 1330 protected Integer doInBackground(Void... params) { 1331 synchronized(mStartLock) { 1332 if (isCancelled()) { 1333 return null; 1334 } 1335 1336 try { 1337 mConnectedService.setCallback(getCallerIdentity(), mCallback); 1338 Log.i(TAG, "Setuped connection to " + mName); 1339 return SUCCESS; 1340 } catch (RemoteException re) { 1341 Log.e(TAG, "Error connecting to service, setCallback() failed"); 1342 return ERROR; 1343 } 1344 } 1345 } 1346 1347 @Override 1348 protected void onPostExecute(Integer result) { 1349 synchronized(mStartLock) { 1350 if (mOnServiceConnectedAsyncTask == this) { 1351 mOnServiceConnectedAsyncTask = null; 1352 } 1353 1354 mServiceConnection = Connection.this; 1355 mService = mConnectedService; 1356 1357 dispatchOnInit(result); 1358 } 1359 } 1360 } 1361 1362 @Override 1363 public void onServiceConnected(ComponentName name, IBinder service) { 1364 synchronized(mStartLock) { 1365 Log.i(TAG, "Connected to " + name); 1366 1367 if (mOnServiceConnectedAsyncTask != null) { 1368 mOnServiceConnectedAsyncTask.cancel(false); 1369 } 1370 1371 mOnServiceConnectedAsyncTask = new OnServiceConnectedAsyncTask(name, service); 1372 mOnServiceConnectedAsyncTask.execute(); 1373 } 1374 } 1375 1376 public IBinder getCallerIdentity() { 1377 return mCallback; 1378 } 1379 1380 /** 1381 * Clear connection related fields and cancel mOnServiceConnectedAsyncTask if set. 1382 * 1383 * @return true if we cancel mOnServiceConnectedAsyncTask in progress. 1384 */ 1385 private boolean clearServiceConnection() { 1386 synchronized(mStartLock) { 1387 boolean result = false; 1388 if (mOnServiceConnectedAsyncTask != null) { 1389 result = mOnServiceConnectedAsyncTask.cancel(false); 1390 mOnServiceConnectedAsyncTask = null; 1391 } 1392 1393 mService = null; 1394 // If this is the active connection, clear it 1395 if (mServiceConnection == this) { 1396 mServiceConnection = null; 1397 } 1398 return result; 1399 } 1400 } 1401 1402 @Override 1403 public void onServiceDisconnected(ComponentName name) { 1404 Log.i(TAG, "Asked to disconnect from " + name); 1405 if (clearServiceConnection()) { 1406 /* We need to protect against a rare case where engine 1407 * dies just after successful connection - and we process onServiceDisconnected 1408 * before OnServiceConnectedAsyncTask.onPostExecute. onServiceDisconnected cancels 1409 * OnServiceConnectedAsyncTask.onPostExecute and we don't call dispatchOnInit 1410 * with ERROR as argument. 1411 */ 1412 dispatchOnInit(ERROR); 1413 } 1414 } 1415 1416 public void disconnect() { 1417 mContext.unbindService(this); 1418 clearServiceConnection(); 1419 } 1420 1421 public <R> R runAction(Action<R> action, R errorResult, String method, boolean reconnect) { 1422 synchronized (mStartLock) { 1423 try { 1424 if (mService == null) { 1425 Log.w(TAG, method + " failed: not connected to TTS engine"); 1426 return errorResult; 1427 } 1428 return action.run(mService); 1429 } catch (RemoteException ex) { 1430 Log.e(TAG, method + " failed", ex); 1431 if (reconnect) { 1432 disconnect(); 1433 initTts(); 1434 } 1435 return errorResult; 1436 } 1437 } 1438 } 1439 } 1440 1441 private interface Action<R> { 1442 R run(ITextToSpeechService service) throws RemoteException; 1443 } 1444 1445 /** 1446 * Information about an installed text-to-speech engine. 1447 * 1448 * @see TextToSpeech#getEngines 1449 */ 1450 public static class EngineInfo { 1451 /** 1452 * Engine package name.. 1453 */ 1454 public String name; 1455 /** 1456 * Localized label for the engine. 1457 */ 1458 public String label; 1459 /** 1460 * Icon for the engine. 1461 */ 1462 public int icon; 1463 /** 1464 * Whether this engine is a part of the system 1465 * image. 1466 * 1467 * @hide 1468 */ 1469 public boolean system; 1470 /** 1471 * The priority the engine declares for the the intent filter 1472 * {@code android.intent.action.TTS_SERVICE} 1473 * 1474 * @hide 1475 */ 1476 public int priority; 1477 1478 @Override 1479 public String toString() { 1480 return "EngineInfo{name=" + name + "}"; 1481 } 1482 1483 } 1484 1485} 1486