TextToSpeech.java revision 176baa7de11be910c36b7b4dfa7826b55ec97963
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. No longer than 806 * {@link #getMaxSpeechInputLength()} characters. 807 * @param queueMode The queuing strategy to use, {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 808 * @param params Parameters for the request. Can be null. 809 * Supported parameter names: 810 * {@link Engine#KEY_PARAM_STREAM}, 811 * {@link Engine#KEY_PARAM_UTTERANCE_ID}, 812 * {@link Engine#KEY_PARAM_VOLUME}, 813 * {@link Engine#KEY_PARAM_PAN}. 814 * Engine specific parameters may be passed in but the parameter keys 815 * must be prefixed by the name of the engine they are intended for. For example 816 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 817 * engine named "com.svox.pico" if it is being used. 818 * 819 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the speak operation. 820 */ 821 public int speak(final String text, final int queueMode, final HashMap<String, String> params) { 822 return runAction(new Action<Integer>() { 823 @Override 824 public Integer run(ITextToSpeechService service) throws RemoteException { 825 Uri utteranceUri = mUtterances.get(text); 826 if (utteranceUri != null) { 827 return service.playAudio(getCallerIdentity(), utteranceUri, queueMode, 828 getParams(params)); 829 } else { 830 return service.speak(getCallerIdentity(), text, queueMode, getParams(params)); 831 } 832 } 833 }, ERROR, "speak"); 834 } 835 836 /** 837 * Plays the earcon using the specified queueing mode and parameters. 838 * The earcon must already have been added with {@link #addEarcon(String, String)} or 839 * {@link #addEarcon(String, String, int)}. 840 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 841 * requests and then returns. The synthesis might not have finished (or even started!) at the 842 * time when this method returns. In order to reliably detect errors during synthesis, 843 * we recommend setting an utterance progress listener (see 844 * {@link #setOnUtteranceProgressListener}) and using the 845 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 846 * 847 * @param earcon The earcon that should be played 848 * @param queueMode {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 849 * @param params Parameters for the request. Can be null. 850 * Supported parameter names: 851 * {@link Engine#KEY_PARAM_STREAM}, 852 * {@link Engine#KEY_PARAM_UTTERANCE_ID}. 853 * Engine specific parameters may be passed in but the parameter keys 854 * must be prefixed by the name of the engine they are intended for. For example 855 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 856 * engine named "com.svox.pico" if it is being used. 857 * 858 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the playEarcon operation. 859 */ 860 public int playEarcon(final String earcon, final int queueMode, 861 final HashMap<String, String> params) { 862 return runAction(new Action<Integer>() { 863 @Override 864 public Integer run(ITextToSpeechService service) throws RemoteException { 865 Uri earconUri = mEarcons.get(earcon); 866 if (earconUri == null) { 867 return ERROR; 868 } 869 return service.playAudio(getCallerIdentity(), earconUri, queueMode, 870 getParams(params)); 871 } 872 }, ERROR, "playEarcon"); 873 } 874 875 /** 876 * Plays silence for the specified amount of time using the specified 877 * queue mode. 878 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 879 * requests and then returns. The synthesis might not have finished (or even started!) at the 880 * time when this method returns. In order to reliably detect errors during synthesis, 881 * we recommend setting an utterance progress listener (see 882 * {@link #setOnUtteranceProgressListener}) and using the 883 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 884 * 885 * @param durationInMs The duration of the silence. 886 * @param queueMode {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}. 887 * @param params Parameters for the request. Can be null. 888 * Supported parameter names: 889 * {@link Engine#KEY_PARAM_UTTERANCE_ID}. 890 * Engine specific parameters may be passed in but the parameter keys 891 * must be prefixed by the name of the engine they are intended for. For example 892 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 893 * engine named "com.svox.pico" if it is being used. 894 * 895 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the playSilence operation. 896 */ 897 public int playSilence(final long durationInMs, final int queueMode, 898 final HashMap<String, String> params) { 899 return runAction(new Action<Integer>() { 900 @Override 901 public Integer run(ITextToSpeechService service) throws RemoteException { 902 return service.playSilence(getCallerIdentity(), durationInMs, queueMode, 903 getParams(params)); 904 } 905 }, ERROR, "playSilence"); 906 } 907 908 /** 909 * Queries the engine for the set of features it supports for a given locale. 910 * Features can either be framework defined, e.g. 911 * {@link TextToSpeech.Engine#KEY_FEATURE_NETWORK_SYNTHESIS} or engine specific. 912 * Engine specific keys must be prefixed by the name of the engine they 913 * are intended for. These keys can be used as parameters to 914 * {@link TextToSpeech#speak(String, int, java.util.HashMap)} and 915 * {@link TextToSpeech#synthesizeToFile(String, java.util.HashMap, String)}. 916 * 917 * Features are boolean flags, and their values in the synthesis parameters 918 * must be behave as per {@link Boolean#parseBoolean(String)}. 919 * 920 * @param locale The locale to query features for. 921 */ 922 public Set<String> getFeatures(final Locale locale) { 923 return runAction(new Action<Set<String>>() { 924 @Override 925 public Set<String> run(ITextToSpeechService service) throws RemoteException { 926 String[] features = service.getFeaturesForLanguage( 927 locale.getISO3Language(), locale.getISO3Country(), locale.getVariant()); 928 if (features != null) { 929 final Set<String> featureSet = new HashSet<String>(); 930 Collections.addAll(featureSet, features); 931 return featureSet; 932 } 933 return null; 934 } 935 }, null, "getFeatures"); 936 } 937 938 /** 939 * Checks whether the TTS engine is busy speaking. Note that a speech item is 940 * considered complete once it's audio data has been sent to the audio mixer, or 941 * written to a file. There might be a finite lag between this point, and when 942 * the audio hardware completes playback. 943 * 944 * @return {@code true} if the TTS engine is speaking. 945 */ 946 public boolean isSpeaking() { 947 return runAction(new Action<Boolean>() { 948 @Override 949 public Boolean run(ITextToSpeechService service) throws RemoteException { 950 return service.isSpeaking(); 951 } 952 }, false, "isSpeaking"); 953 } 954 955 /** 956 * Interrupts the current utterance (whether played or rendered to file) and discards other 957 * utterances in the queue. 958 * 959 * @return {@link #ERROR} or {@link #SUCCESS}. 960 */ 961 public int stop() { 962 return runAction(new Action<Integer>() { 963 @Override 964 public Integer run(ITextToSpeechService service) throws RemoteException { 965 return service.stop(getCallerIdentity()); 966 } 967 }, ERROR, "stop"); 968 } 969 970 /** 971 * Sets the speech rate. 972 * 973 * This has no effect on any pre-recorded speech. 974 * 975 * @param speechRate Speech rate. {@code 1.0} is the normal speech rate, 976 * lower values slow down the speech ({@code 0.5} is half the normal speech rate), 977 * greater values accelerate it ({@code 2.0} is twice the normal speech rate). 978 * 979 * @return {@link #ERROR} or {@link #SUCCESS}. 980 */ 981 public int setSpeechRate(float speechRate) { 982 if (speechRate > 0.0f) { 983 int intRate = (int)(speechRate * 100); 984 if (intRate > 0) { 985 synchronized (mStartLock) { 986 mParams.putInt(Engine.KEY_PARAM_RATE, intRate); 987 } 988 return SUCCESS; 989 } 990 } 991 return ERROR; 992 } 993 994 /** 995 * Sets the speech pitch for the TextToSpeech engine. 996 * 997 * This has no effect on any pre-recorded speech. 998 * 999 * @param pitch Speech pitch. {@code 1.0} is the normal pitch, 1000 * lower values lower the tone of the synthesized voice, 1001 * greater values increase it. 1002 * 1003 * @return {@link #ERROR} or {@link #SUCCESS}. 1004 */ 1005 public int setPitch(float pitch) { 1006 if (pitch > 0.0f) { 1007 int intPitch = (int)(pitch * 100); 1008 if (intPitch > 0) { 1009 synchronized (mStartLock) { 1010 mParams.putInt(Engine.KEY_PARAM_PITCH, intPitch); 1011 } 1012 return SUCCESS; 1013 } 1014 } 1015 return ERROR; 1016 } 1017 1018 /** 1019 * @return the engine currently in use by this TextToSpeech instance. 1020 * @hide 1021 */ 1022 public String getCurrentEngine() { 1023 return mCurrentEngine; 1024 } 1025 1026 /** 1027 * Returns a Locale instance describing the language currently being used as the default 1028 * Text-to-speech language. 1029 * 1030 * @return language, country (if any) and variant (if any) used by the client stored in a 1031 * Locale instance, or {@code null} on error. 1032 */ 1033 public Locale getDefaultLanguage() { 1034 return runAction(new Action<Locale>() { 1035 @Override 1036 public Locale run(ITextToSpeechService service) throws RemoteException { 1037 String[] defaultLanguage = service.getClientDefaultLanguage(); 1038 1039 return new Locale(defaultLanguage[0], defaultLanguage[1], defaultLanguage[2]); 1040 } 1041 }, null, "getDefaultLanguage"); 1042 } 1043 1044 /** 1045 * Sets the text-to-speech language. 1046 * The TTS engine will try to use the closest match to the specified 1047 * language as represented by the Locale, but there is no guarantee that the exact same Locale 1048 * will be used. Use {@link #isLanguageAvailable(Locale)} to check the level of support 1049 * before choosing the language to use for the next utterances. 1050 * 1051 * @param loc The locale describing the language to be used. 1052 * 1053 * @return Code indicating the support status for the locale. See {@link #LANG_AVAILABLE}, 1054 * {@link #LANG_COUNTRY_AVAILABLE}, {@link #LANG_COUNTRY_VAR_AVAILABLE}, 1055 * {@link #LANG_MISSING_DATA} and {@link #LANG_NOT_SUPPORTED}. 1056 */ 1057 public int setLanguage(final Locale loc) { 1058 return runAction(new Action<Integer>() { 1059 @Override 1060 public Integer run(ITextToSpeechService service) throws RemoteException { 1061 if (loc == null) { 1062 return LANG_NOT_SUPPORTED; 1063 } 1064 String language = loc.getISO3Language(); 1065 String country = loc.getISO3Country(); 1066 String variant = loc.getVariant(); 1067 // Check if the language, country, variant are available, and cache 1068 // the available parts. 1069 // Note that the language is not actually set here, instead it is cached so it 1070 // will be associated with all upcoming utterances. 1071 1072 int result = service.loadLanguage(getCallerIdentity(), language, country, variant); 1073 if (result >= LANG_AVAILABLE){ 1074 if (result < LANG_COUNTRY_VAR_AVAILABLE) { 1075 variant = ""; 1076 if (result < LANG_COUNTRY_AVAILABLE) { 1077 country = ""; 1078 } 1079 } 1080 mParams.putString(Engine.KEY_PARAM_LANGUAGE, language); 1081 mParams.putString(Engine.KEY_PARAM_COUNTRY, country); 1082 mParams.putString(Engine.KEY_PARAM_VARIANT, variant); 1083 } 1084 return result; 1085 } 1086 }, LANG_NOT_SUPPORTED, "setLanguage"); 1087 } 1088 1089 /** 1090 * Returns a Locale instance describing the language currently being used for synthesis 1091 * requests sent to the TextToSpeech engine. 1092 * 1093 * In Android 4.2 and before (API <= 17) this function returns the language that is currently 1094 * being used by the TTS engine. That is the last language set by this or any other 1095 * client by a {@link TextToSpeech#setLanguage} call to the same engine. 1096 * 1097 * In Android versions after 4.2 this function returns the language that is currently being 1098 * used for the synthesis requests sent from this client. That is the last language set 1099 * by a {@link TextToSpeech#setLanguage} call on this instance. 1100 * 1101 * @return language, country (if any) and variant (if any) used by the client stored in a 1102 * Locale instance, or {@code null} on error. 1103 */ 1104 public Locale getLanguage() { 1105 return runAction(new Action<Locale>() { 1106 @Override 1107 public Locale run(ITextToSpeechService service) { 1108 /* No service call, but we're accessing mParams, hence need for 1109 wrapping it as an Action instance */ 1110 String lang = mParams.getString(Engine.KEY_PARAM_LANGUAGE, ""); 1111 String country = mParams.getString(Engine.KEY_PARAM_COUNTRY, ""); 1112 String variant = mParams.getString(Engine.KEY_PARAM_VARIANT, ""); 1113 return new Locale(lang, country, variant); 1114 } 1115 }, null, "getLanguage"); 1116 } 1117 1118 /** 1119 * Checks if the specified language as represented by the Locale is available and supported. 1120 * 1121 * @param loc The Locale describing the language to be used. 1122 * 1123 * @return Code indicating the support status for the locale. See {@link #LANG_AVAILABLE}, 1124 * {@link #LANG_COUNTRY_AVAILABLE}, {@link #LANG_COUNTRY_VAR_AVAILABLE}, 1125 * {@link #LANG_MISSING_DATA} and {@link #LANG_NOT_SUPPORTED}. 1126 */ 1127 public int isLanguageAvailable(final Locale loc) { 1128 return runAction(new Action<Integer>() { 1129 @Override 1130 public Integer run(ITextToSpeechService service) throws RemoteException { 1131 return service.isLanguageAvailable(loc.getISO3Language(), 1132 loc.getISO3Country(), loc.getVariant()); 1133 } 1134 }, LANG_NOT_SUPPORTED, "isLanguageAvailable"); 1135 } 1136 1137 /** 1138 * Synthesizes the given text to a file using the specified parameters. 1139 * This method is asynchronous, i.e. the method just adds the request to the queue of TTS 1140 * requests and then returns. The synthesis might not have finished (or even started!) at the 1141 * time when this method returns. In order to reliably detect errors during synthesis, 1142 * we recommend setting an utterance progress listener (see 1143 * {@link #setOnUtteranceProgressListener}) and using the 1144 * {@link Engine#KEY_PARAM_UTTERANCE_ID} parameter. 1145 * 1146 * @param text The text that should be synthesized. No longer than 1147 * {@link #getMaxSpeechInputLength()} characters. 1148 * @param params Parameters for the request. Can be null. 1149 * Supported parameter names: 1150 * {@link Engine#KEY_PARAM_UTTERANCE_ID}. 1151 * Engine specific parameters may be passed in but the parameter keys 1152 * must be prefixed by the name of the engine they are intended for. For example 1153 * the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the 1154 * engine named "com.svox.pico" if it is being used. 1155 * @param filename Absolute file filename to write the generated audio data to.It should be 1156 * something like "/sdcard/myappsounds/mysound.wav". 1157 * 1158 * @return {@link #ERROR} or {@link #SUCCESS} of <b>queuing</b> the synthesizeToFile operation. 1159 */ 1160 public int synthesizeToFile(final String text, final HashMap<String, String> params, 1161 final String filename) { 1162 return runAction(new Action<Integer>() { 1163 @Override 1164 public Integer run(ITextToSpeechService service) throws RemoteException { 1165 return service.synthesizeToFile(getCallerIdentity(), text, filename, 1166 getParams(params)); 1167 } 1168 }, ERROR, "synthesizeToFile"); 1169 } 1170 1171 private Bundle getParams(HashMap<String, String> params) { 1172 if (params != null && !params.isEmpty()) { 1173 Bundle bundle = new Bundle(mParams); 1174 copyIntParam(bundle, params, Engine.KEY_PARAM_STREAM); 1175 copyStringParam(bundle, params, Engine.KEY_PARAM_UTTERANCE_ID); 1176 copyFloatParam(bundle, params, Engine.KEY_PARAM_VOLUME); 1177 copyFloatParam(bundle, params, Engine.KEY_PARAM_PAN); 1178 1179 // Copy feature strings defined by the framework. 1180 copyStringParam(bundle, params, Engine.KEY_FEATURE_NETWORK_SYNTHESIS); 1181 copyStringParam(bundle, params, Engine.KEY_FEATURE_EMBEDDED_SYNTHESIS); 1182 1183 // Copy over all parameters that start with the name of the 1184 // engine that we are currently connected to. The engine is 1185 // free to interpret them as it chooses. 1186 if (!TextUtils.isEmpty(mCurrentEngine)) { 1187 for (Map.Entry<String, String> entry : params.entrySet()) { 1188 final String key = entry.getKey(); 1189 if (key != null && key.startsWith(mCurrentEngine)) { 1190 bundle.putString(key, entry.getValue()); 1191 } 1192 } 1193 } 1194 1195 return bundle; 1196 } else { 1197 return mParams; 1198 } 1199 } 1200 1201 private void copyStringParam(Bundle bundle, HashMap<String, String> params, String key) { 1202 String value = params.get(key); 1203 if (value != null) { 1204 bundle.putString(key, value); 1205 } 1206 } 1207 1208 private void copyIntParam(Bundle bundle, HashMap<String, String> params, String key) { 1209 String valueString = params.get(key); 1210 if (!TextUtils.isEmpty(valueString)) { 1211 try { 1212 int value = Integer.parseInt(valueString); 1213 bundle.putInt(key, value); 1214 } catch (NumberFormatException ex) { 1215 // don't set the value in the bundle 1216 } 1217 } 1218 } 1219 1220 private void copyFloatParam(Bundle bundle, HashMap<String, String> params, String key) { 1221 String valueString = params.get(key); 1222 if (!TextUtils.isEmpty(valueString)) { 1223 try { 1224 float value = Float.parseFloat(valueString); 1225 bundle.putFloat(key, value); 1226 } catch (NumberFormatException ex) { 1227 // don't set the value in the bundle 1228 } 1229 } 1230 } 1231 1232 /** 1233 * Sets the listener that will be notified when synthesis of an utterance completes. 1234 * 1235 * @param listener The listener to use. 1236 * 1237 * @return {@link #ERROR} or {@link #SUCCESS}. 1238 * 1239 * @deprecated Use {@link #setOnUtteranceProgressListener(UtteranceProgressListener)} 1240 * instead. 1241 */ 1242 @Deprecated 1243 public int setOnUtteranceCompletedListener(final OnUtteranceCompletedListener listener) { 1244 mUtteranceProgressListener = UtteranceProgressListener.from(listener); 1245 return TextToSpeech.SUCCESS; 1246 } 1247 1248 /** 1249 * Sets the listener that will be notified of various events related to the 1250 * synthesis of a given utterance. 1251 * 1252 * See {@link UtteranceProgressListener} and 1253 * {@link TextToSpeech.Engine#KEY_PARAM_UTTERANCE_ID}. 1254 * 1255 * @param listener the listener to use. 1256 * @return {@link #ERROR} or {@link #SUCCESS} 1257 */ 1258 public int setOnUtteranceProgressListener(UtteranceProgressListener listener) { 1259 mUtteranceProgressListener = listener; 1260 return TextToSpeech.SUCCESS; 1261 } 1262 1263 /** 1264 * Sets the TTS engine to use. 1265 * 1266 * @deprecated This doesn't inform callers when the TTS engine has been 1267 * initialized. {@link #TextToSpeech(Context, OnInitListener, String)} 1268 * can be used with the appropriate engine name. Also, there is no 1269 * guarantee that the engine specified will be loaded. If it isn't 1270 * installed or disabled, the user / system wide defaults will apply. 1271 * 1272 * @param enginePackageName The package name for the synthesis engine (e.g. "com.svox.pico") 1273 * 1274 * @return {@link #ERROR} or {@link #SUCCESS}. 1275 */ 1276 @Deprecated 1277 public int setEngineByPackageName(String enginePackageName) { 1278 mRequestedEngine = enginePackageName; 1279 return initTts(); 1280 } 1281 1282 /** 1283 * Gets the package name of the default speech synthesis engine. 1284 * 1285 * @return Package name of the TTS engine that the user has chosen 1286 * as their default. 1287 */ 1288 public String getDefaultEngine() { 1289 return mEnginesHelper.getDefaultEngine(); 1290 } 1291 1292 /** 1293 * Checks whether the user's settings should override settings requested 1294 * by the calling application. As of the Ice cream sandwich release, 1295 * user settings never forcibly override the app's settings. 1296 */ 1297 public boolean areDefaultsEnforced() { 1298 return false; 1299 } 1300 1301 /** 1302 * Gets a list of all installed TTS engines. 1303 * 1304 * @return A list of engine info objects. The list can be empty, but never {@code null}. 1305 */ 1306 public List<EngineInfo> getEngines() { 1307 return mEnginesHelper.getEngines(); 1308 } 1309 1310 private class Connection implements ServiceConnection { 1311 private ITextToSpeechService mService; 1312 1313 private OnServiceConnectedAsyncTask mOnServiceConnectedAsyncTask; 1314 1315 private final ITextToSpeechCallback.Stub mCallback = new ITextToSpeechCallback.Stub() { 1316 @Override 1317 public void onDone(String utteranceId) { 1318 UtteranceProgressListener listener = mUtteranceProgressListener; 1319 if (listener != null) { 1320 listener.onDone(utteranceId); 1321 } 1322 } 1323 1324 @Override 1325 public void onError(String utteranceId) { 1326 UtteranceProgressListener listener = mUtteranceProgressListener; 1327 if (listener != null) { 1328 listener.onError(utteranceId); 1329 } 1330 } 1331 1332 @Override 1333 public void onStart(String utteranceId) { 1334 UtteranceProgressListener listener = mUtteranceProgressListener; 1335 if (listener != null) { 1336 listener.onStart(utteranceId); 1337 } 1338 } 1339 }; 1340 1341 private class OnServiceConnectedAsyncTask extends AsyncTask<Void, Void, Integer> { 1342 private final ComponentName mName; 1343 private final ITextToSpeechService mConnectedService; 1344 1345 public OnServiceConnectedAsyncTask(ComponentName name, IBinder service) { 1346 mName = name; 1347 mConnectedService = ITextToSpeechService.Stub.asInterface(service); 1348 } 1349 1350 @Override 1351 protected Integer doInBackground(Void... params) { 1352 synchronized(mStartLock) { 1353 if (isCancelled()) { 1354 return null; 1355 } 1356 1357 try { 1358 mConnectedService.setCallback(getCallerIdentity(), mCallback); 1359 String[] defaultLanguage = mConnectedService.getClientDefaultLanguage(); 1360 1361 mParams.putString(Engine.KEY_PARAM_LANGUAGE, defaultLanguage[0]); 1362 mParams.putString(Engine.KEY_PARAM_COUNTRY, defaultLanguage[1]); 1363 mParams.putString(Engine.KEY_PARAM_VARIANT, defaultLanguage[2]); 1364 1365 Log.i(TAG, "Set up connection to " + mName); 1366 return SUCCESS; 1367 } catch (RemoteException re) { 1368 Log.e(TAG, "Error connecting to service, setCallback() failed"); 1369 return ERROR; 1370 } 1371 } 1372 } 1373 1374 @Override 1375 protected void onPostExecute(Integer result) { 1376 synchronized(mStartLock) { 1377 if (mOnServiceConnectedAsyncTask == this) { 1378 mOnServiceConnectedAsyncTask = null; 1379 } 1380 1381 mServiceConnection = Connection.this; 1382 mService = mConnectedService; 1383 1384 dispatchOnInit(result); 1385 } 1386 } 1387 } 1388 1389 @Override 1390 public void onServiceConnected(ComponentName name, IBinder service) { 1391 synchronized(mStartLock) { 1392 Log.i(TAG, "Connected to " + name); 1393 1394 if (mOnServiceConnectedAsyncTask != null) { 1395 mOnServiceConnectedAsyncTask.cancel(false); 1396 } 1397 1398 mOnServiceConnectedAsyncTask = new OnServiceConnectedAsyncTask(name, service); 1399 mOnServiceConnectedAsyncTask.execute(); 1400 } 1401 } 1402 1403 public IBinder getCallerIdentity() { 1404 return mCallback; 1405 } 1406 1407 /** 1408 * Clear connection related fields and cancel mOnServiceConnectedAsyncTask if set. 1409 * 1410 * @return true if we cancel mOnServiceConnectedAsyncTask in progress. 1411 */ 1412 private boolean clearServiceConnection() { 1413 synchronized(mStartLock) { 1414 boolean result = false; 1415 if (mOnServiceConnectedAsyncTask != null) { 1416 result = mOnServiceConnectedAsyncTask.cancel(false); 1417 mOnServiceConnectedAsyncTask = null; 1418 } 1419 1420 mService = null; 1421 // If this is the active connection, clear it 1422 if (mServiceConnection == this) { 1423 mServiceConnection = null; 1424 } 1425 return result; 1426 } 1427 } 1428 1429 @Override 1430 public void onServiceDisconnected(ComponentName name) { 1431 Log.i(TAG, "Asked to disconnect from " + name); 1432 if (clearServiceConnection()) { 1433 /* We need to protect against a rare case where engine 1434 * dies just after successful connection - and we process onServiceDisconnected 1435 * before OnServiceConnectedAsyncTask.onPostExecute. onServiceDisconnected cancels 1436 * OnServiceConnectedAsyncTask.onPostExecute and we don't call dispatchOnInit 1437 * with ERROR as argument. 1438 */ 1439 dispatchOnInit(ERROR); 1440 } 1441 } 1442 1443 public void disconnect() { 1444 mContext.unbindService(this); 1445 clearServiceConnection(); 1446 } 1447 1448 public <R> R runAction(Action<R> action, R errorResult, String method, boolean reconnect) { 1449 synchronized (mStartLock) { 1450 try { 1451 if (mService == null) { 1452 Log.w(TAG, method + " failed: not connected to TTS engine"); 1453 return errorResult; 1454 } 1455 return action.run(mService); 1456 } catch (RemoteException ex) { 1457 Log.e(TAG, method + " failed", ex); 1458 if (reconnect) { 1459 disconnect(); 1460 initTts(); 1461 } 1462 return errorResult; 1463 } 1464 } 1465 } 1466 } 1467 1468 private interface Action<R> { 1469 R run(ITextToSpeechService service) throws RemoteException; 1470 } 1471 1472 /** 1473 * Information about an installed text-to-speech engine. 1474 * 1475 * @see TextToSpeech#getEngines 1476 */ 1477 public static class EngineInfo { 1478 /** 1479 * Engine package name.. 1480 */ 1481 public String name; 1482 /** 1483 * Localized label for the engine. 1484 */ 1485 public String label; 1486 /** 1487 * Icon for the engine. 1488 */ 1489 public int icon; 1490 /** 1491 * Whether this engine is a part of the system 1492 * image. 1493 * 1494 * @hide 1495 */ 1496 public boolean system; 1497 /** 1498 * The priority the engine declares for the the intent filter 1499 * {@code android.intent.action.TTS_SERVICE} 1500 * 1501 * @hide 1502 */ 1503 public int priority; 1504 1505 @Override 1506 public String toString() { 1507 return "EngineInfo{name=" + name + "}"; 1508 } 1509 1510 } 1511 1512 /** 1513 * Limit of length of input string passed to speak and synthesizeToFile. 1514 * 1515 * @see #speak 1516 * @see #synthesizeToFile 1517 */ 1518 public static int getMaxSpeechInputLength() { 1519 return 4000; 1520 } 1521} 1522