TextToSpeechService.java revision 90e5650f96dabadaaf141beae20a646855073ae1
1/* 2 * Copyright (C) 2011 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.app.Service; 19import android.content.Intent; 20import android.net.Uri; 21import android.os.Bundle; 22import android.os.Handler; 23import android.os.HandlerThread; 24import android.os.IBinder; 25import android.os.Looper; 26import android.os.Message; 27import android.os.MessageQueue; 28import android.os.RemoteCallbackList; 29import android.os.RemoteException; 30import android.provider.Settings; 31import android.speech.tts.TextToSpeech.Engine; 32import android.text.TextUtils; 33import android.util.Log; 34 35import java.io.File; 36import java.io.IOException; 37import java.util.HashMap; 38import java.util.Locale; 39 40 41/** 42 * Abstract base class for TTS engine implementations. The following methods 43 * need to be implemented. 44 * 45 * <ul> 46 * <li>{@link #onIsLanguageAvailable}</li> 47 * <li>{@link #onLoadLanguage}</li> 48 * <li>{@link #onGetLanguage}</li> 49 * <li>{@link #onSynthesizeText}</li> 50 * <li>{@link #onStop}</li> 51 * </ul> 52 * 53 * The first three deal primarily with language management, and are used to 54 * query the engine for it's support for a given language and indicate to it 55 * that requests in a given language are imminent. 56 * 57 * {@link #onSynthesizeText} is central to the engine implementation. The 58 * implementation should synthesize text as per the request parameters and 59 * return synthesized data via the supplied callback. This class and its helpers 60 * will then consume that data, which might mean queueing it for playback or writing 61 * it to a file or similar. All calls to this method will be on a single 62 * thread, which will be different from the main thread of the service. Synthesis 63 * must be synchronous which means the engine must NOT hold on the callback or call 64 * any methods on it after the method returns 65 * 66 * {@link #onStop} tells the engine that it should stop all ongoing synthesis, if 67 * any. Any pending data from the current synthesis will be discarded. 68 */ 69// TODO: Add a link to the sample TTS engine once it's done. 70public abstract class TextToSpeechService extends Service { 71 72 private static final boolean DBG = false; 73 private static final String TAG = "TextToSpeechService"; 74 75 private static final int MAX_SPEECH_ITEM_CHAR_LENGTH = 4000; 76 private static final String SYNTH_THREAD_NAME = "SynthThread"; 77 78 private SynthHandler mSynthHandler; 79 // A thread and it's associated handler for playing back any audio 80 // associated with this TTS engine. Will handle all requests except synthesis 81 // to file requests, which occur on the synthesis thread. 82 private AudioPlaybackHandler mAudioPlaybackHandler; 83 84 private CallbackMap mCallbacks; 85 private String mPackageName; 86 87 @Override 88 public void onCreate() { 89 if (DBG) Log.d(TAG, "onCreate()"); 90 super.onCreate(); 91 92 SynthThread synthThread = new SynthThread(); 93 synthThread.start(); 94 mSynthHandler = new SynthHandler(synthThread.getLooper()); 95 96 mAudioPlaybackHandler = new AudioPlaybackHandler(); 97 mAudioPlaybackHandler.start(); 98 99 mCallbacks = new CallbackMap(); 100 101 mPackageName = getApplicationInfo().packageName; 102 103 // Load default language 104 onLoadLanguage(getDefaultLanguage(), getDefaultCountry(), getDefaultVariant()); 105 } 106 107 @Override 108 public void onDestroy() { 109 if (DBG) Log.d(TAG, "onDestroy()"); 110 111 // Tell the synthesizer to stop 112 mSynthHandler.quit(); 113 // Tell the audio playback thread to stop. 114 mAudioPlaybackHandler.quit(); 115 // Unregister all callbacks. 116 mCallbacks.kill(); 117 118 super.onDestroy(); 119 } 120 121 /** 122 * Checks whether the engine supports a given language. 123 * 124 * Can be called on multiple threads. 125 * 126 * @param lang ISO-3 language code. 127 * @param country ISO-3 country code. May be empty or null. 128 * @param variant Language variant. May be empty or null. 129 * @return Code indicating the support status for the locale. 130 * One of {@link TextToSpeech#LANG_AVAILABLE}, 131 * {@link TextToSpeech#LANG_COUNTRY_AVAILABLE}, 132 * {@link TextToSpeech#LANG_COUNTRY_VAR_AVAILABLE}, 133 * {@link TextToSpeech#LANG_MISSING_DATA} 134 * {@link TextToSpeech#LANG_NOT_SUPPORTED}. 135 */ 136 protected abstract int onIsLanguageAvailable(String lang, String country, String variant); 137 138 /** 139 * Returns the language, country and variant currently being used by the TTS engine. 140 * 141 * Can be called on multiple threads. 142 * 143 * @return A 3-element array, containing language (ISO 3-letter code), 144 * country (ISO 3-letter code) and variant used by the engine. 145 * The country and variant may be {@code ""}. If country is empty, then variant must 146 * be empty too. 147 * @see Locale#getISO3Language() 148 * @see Locale#getISO3Country() 149 * @see Locale#getVariant() 150 */ 151 protected abstract String[] onGetLanguage(); 152 153 /** 154 * Notifies the engine that it should load a speech synthesis language. There is no guarantee 155 * that this method is always called before the language is used for synthesis. It is merely 156 * a hint to the engine that it will probably get some synthesis requests for this language 157 * at some point in the future. 158 * 159 * Can be called on multiple threads. 160 * 161 * @param lang ISO-3 language code. 162 * @param country ISO-3 country code. May be empty or null. 163 * @param variant Language variant. May be empty or null. 164 * @return Code indicating the support status for the locale. 165 * One of {@link TextToSpeech#LANG_AVAILABLE}, 166 * {@link TextToSpeech#LANG_COUNTRY_AVAILABLE}, 167 * {@link TextToSpeech#LANG_COUNTRY_VAR_AVAILABLE}, 168 * {@link TextToSpeech#LANG_MISSING_DATA} 169 * {@link TextToSpeech#LANG_NOT_SUPPORTED}. 170 */ 171 protected abstract int onLoadLanguage(String lang, String country, String variant); 172 173 /** 174 * Notifies the service that it should stop any in-progress speech synthesis. 175 * This method can be called even if no speech synthesis is currently in progress. 176 * 177 * Can be called on multiple threads, but not on the synthesis thread. 178 */ 179 protected abstract void onStop(); 180 181 /** 182 * Tells the service to synthesize speech from the given text. This method should 183 * block until the synthesis is finished. 184 * 185 * Called on the synthesis thread. 186 * 187 * @param request The synthesis request. 188 * @param callback The callback the the engine must use to make data available for 189 * playback or for writing to a file. 190 */ 191 protected abstract void onSynthesizeText(SynthesisRequest request, 192 SynthesisCallback callback); 193 194 private int getDefaultSpeechRate() { 195 return getSecureSettingInt(Settings.Secure.TTS_DEFAULT_RATE, Engine.DEFAULT_RATE); 196 } 197 198 private String getDefaultLanguage() { 199 return getSecureSettingString(Settings.Secure.TTS_DEFAULT_LANG, 200 Locale.getDefault().getISO3Language()); 201 } 202 203 private String getDefaultCountry() { 204 return getSecureSettingString(Settings.Secure.TTS_DEFAULT_COUNTRY, 205 Locale.getDefault().getISO3Country()); 206 } 207 208 private String getDefaultVariant() { 209 return getSecureSettingString(Settings.Secure.TTS_DEFAULT_VARIANT, 210 Locale.getDefault().getVariant()); 211 } 212 213 private int getSecureSettingInt(String name, int defaultValue) { 214 return Settings.Secure.getInt(getContentResolver(), name, defaultValue); 215 } 216 217 private String getSecureSettingString(String name, String defaultValue) { 218 String value = Settings.Secure.getString(getContentResolver(), name); 219 return value != null ? value : defaultValue; 220 } 221 222 /** 223 * Synthesizer thread. This thread is used to run {@link SynthHandler}. 224 */ 225 private class SynthThread extends HandlerThread implements MessageQueue.IdleHandler { 226 227 private boolean mFirstIdle = true; 228 229 public SynthThread() { 230 super(SYNTH_THREAD_NAME, android.os.Process.THREAD_PRIORITY_AUDIO); 231 } 232 233 @Override 234 protected void onLooperPrepared() { 235 getLooper().getQueue().addIdleHandler(this); 236 } 237 238 @Override 239 public boolean queueIdle() { 240 if (mFirstIdle) { 241 mFirstIdle = false; 242 } else { 243 broadcastTtsQueueProcessingCompleted(); 244 } 245 return true; 246 } 247 248 private void broadcastTtsQueueProcessingCompleted() { 249 Intent i = new Intent(TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED); 250 if (DBG) Log.d(TAG, "Broadcasting: " + i); 251 sendBroadcast(i); 252 } 253 } 254 255 private class SynthHandler extends Handler { 256 257 private SpeechItem mCurrentSpeechItem = null; 258 259 public SynthHandler(Looper looper) { 260 super(looper); 261 } 262 263 private synchronized SpeechItem getCurrentSpeechItem() { 264 return mCurrentSpeechItem; 265 } 266 267 private synchronized SpeechItem setCurrentSpeechItem(SpeechItem speechItem) { 268 SpeechItem old = mCurrentSpeechItem; 269 mCurrentSpeechItem = speechItem; 270 return old; 271 } 272 273 public boolean isSpeaking() { 274 return getCurrentSpeechItem() != null; 275 } 276 277 public void quit() { 278 // Don't process any more speech items 279 getLooper().quit(); 280 // Stop the current speech item 281 SpeechItem current = setCurrentSpeechItem(null); 282 if (current != null) { 283 current.stop(); 284 } 285 286 // The AudioPlaybackHandler will be destroyed by the caller. 287 } 288 289 /** 290 * Adds a speech item to the queue. 291 * 292 * Called on a service binder thread. 293 */ 294 public int enqueueSpeechItem(int queueMode, final SpeechItem speechItem) { 295 if (!speechItem.isValid()) { 296 return TextToSpeech.ERROR; 297 } 298 299 if (queueMode == TextToSpeech.QUEUE_FLUSH) { 300 stop(speechItem.getCallingApp()); 301 } else if (queueMode == TextToSpeech.QUEUE_DESTROY) { 302 // Stop the current speech item. 303 stop(speechItem.getCallingApp()); 304 // Remove all other items from the queue. 305 removeCallbacksAndMessages(null); 306 // Remove all pending playback as well. 307 mAudioPlaybackHandler.removeAllItems(); 308 } 309 Runnable runnable = new Runnable() { 310 @Override 311 public void run() { 312 setCurrentSpeechItem(speechItem); 313 speechItem.play(); 314 setCurrentSpeechItem(null); 315 } 316 }; 317 Message msg = Message.obtain(this, runnable); 318 // The obj is used to remove all callbacks from the given app in stop(String). 319 // 320 // Note that this string is interned, so the == comparison works. 321 msg.obj = speechItem.getCallingApp(); 322 if (sendMessage(msg)) { 323 return TextToSpeech.SUCCESS; 324 } else { 325 Log.w(TAG, "SynthThread has quit"); 326 return TextToSpeech.ERROR; 327 } 328 } 329 330 /** 331 * Stops all speech output and removes any utterances still in the queue for 332 * the calling app. 333 * 334 * Called on a service binder thread. 335 */ 336 public int stop(String callingApp) { 337 if (TextUtils.isEmpty(callingApp)) { 338 return TextToSpeech.ERROR; 339 } 340 341 removeCallbacksAndMessages(callingApp); 342 // This stops writing data to the file / or publishing 343 // items to the audio playback handler. 344 SpeechItem current = setCurrentSpeechItem(null); 345 if (current != null && TextUtils.equals(callingApp, current.getCallingApp())) { 346 current.stop(); 347 } 348 349 // Remove any enqueued audio too. 350 mAudioPlaybackHandler.removePlaybackItems(callingApp); 351 352 return TextToSpeech.SUCCESS; 353 } 354 } 355 356 interface UtteranceCompletedDispatcher { 357 public void dispatchUtteranceCompleted(); 358 } 359 360 /** 361 * An item in the synth thread queue. 362 */ 363 private abstract class SpeechItem implements UtteranceCompletedDispatcher { 364 private final String mCallingApp; 365 protected final Bundle mParams; 366 private boolean mStarted = false; 367 private boolean mStopped = false; 368 369 public SpeechItem(String callingApp, Bundle params) { 370 mCallingApp = callingApp; 371 mParams = params; 372 } 373 374 public String getCallingApp() { 375 return mCallingApp; 376 } 377 378 /** 379 * Checker whether the item is valid. If this method returns false, the item should not 380 * be played. 381 */ 382 public abstract boolean isValid(); 383 384 /** 385 * Plays the speech item. Blocks until playback is finished. 386 * Must not be called more than once. 387 * 388 * Only called on the synthesis thread. 389 * 390 * @return {@link TextToSpeech#SUCCESS} or {@link TextToSpeech#ERROR}. 391 */ 392 public int play() { 393 synchronized (this) { 394 if (mStarted) { 395 throw new IllegalStateException("play() called twice"); 396 } 397 mStarted = true; 398 } 399 return playImpl(); 400 } 401 402 /** 403 * Stops the speech item. 404 * Must not be called more than once. 405 * 406 * Can be called on multiple threads, but not on the synthesis thread. 407 */ 408 public void stop() { 409 synchronized (this) { 410 if (mStopped) { 411 throw new IllegalStateException("stop() called twice"); 412 } 413 mStopped = true; 414 } 415 stopImpl(); 416 } 417 418 public void dispatchUtteranceCompleted() { 419 final String utteranceId = getUtteranceId(); 420 if (!TextUtils.isEmpty(utteranceId)) { 421 mCallbacks.dispatchUtteranceCompleted(getCallingApp(), utteranceId); 422 } 423 } 424 425 protected abstract int playImpl(); 426 427 protected abstract void stopImpl(); 428 429 public int getStreamType() { 430 return getIntParam(Engine.KEY_PARAM_STREAM, Engine.DEFAULT_STREAM); 431 } 432 433 public float getVolume() { 434 return getFloatParam(Engine.KEY_PARAM_VOLUME, Engine.DEFAULT_VOLUME); 435 } 436 437 public float getPan() { 438 return getFloatParam(Engine.KEY_PARAM_PAN, Engine.DEFAULT_PAN); 439 } 440 441 public String getUtteranceId() { 442 return getStringParam(Engine.KEY_PARAM_UTTERANCE_ID, null); 443 } 444 445 protected String getStringParam(String key, String defaultValue) { 446 return mParams == null ? defaultValue : mParams.getString(key, defaultValue); 447 } 448 449 protected int getIntParam(String key, int defaultValue) { 450 return mParams == null ? defaultValue : mParams.getInt(key, defaultValue); 451 } 452 453 protected float getFloatParam(String key, float defaultValue) { 454 return mParams == null ? defaultValue : mParams.getFloat(key, defaultValue); 455 } 456 } 457 458 class SynthesisSpeechItem extends SpeechItem { 459 private final String mText; 460 private final SynthesisRequest mSynthesisRequest; 461 // Non null after synthesis has started, and all accesses 462 // guarded by 'this'. 463 private AbstractSynthesisCallback mSynthesisCallback; 464 private final EventLogger mEventLogger; 465 466 public SynthesisSpeechItem(String callingApp, Bundle params, String text) { 467 super(callingApp, params); 468 mText = text; 469 mSynthesisRequest = new SynthesisRequest(mText, mParams); 470 setRequestParams(mSynthesisRequest); 471 mEventLogger = new EventLogger(mSynthesisRequest, getCallingApp(), mPackageName); 472 } 473 474 public String getText() { 475 return mText; 476 } 477 478 @Override 479 public boolean isValid() { 480 if (TextUtils.isEmpty(mText)) { 481 Log.w(TAG, "Got empty text"); 482 return false; 483 } 484 if (mText.length() >= MAX_SPEECH_ITEM_CHAR_LENGTH){ 485 Log.w(TAG, "Text too long: " + mText.length() + " chars"); 486 return false; 487 } 488 return true; 489 } 490 491 @Override 492 protected int playImpl() { 493 AbstractSynthesisCallback synthesisCallback; 494 mEventLogger.onRequestProcessingStart(); 495 synchronized (this) { 496 mSynthesisCallback = createSynthesisCallback(); 497 synthesisCallback = mSynthesisCallback; 498 } 499 TextToSpeechService.this.onSynthesizeText(mSynthesisRequest, synthesisCallback); 500 return synthesisCallback.isDone() ? TextToSpeech.SUCCESS : TextToSpeech.ERROR; 501 } 502 503 protected AbstractSynthesisCallback createSynthesisCallback() { 504 return new PlaybackSynthesisCallback(getStreamType(), getVolume(), getPan(), 505 mAudioPlaybackHandler, this, getCallingApp(), mEventLogger); 506 } 507 508 private void setRequestParams(SynthesisRequest request) { 509 request.setLanguage(getLanguage(), getCountry(), getVariant()); 510 request.setSpeechRate(getSpeechRate()); 511 512 request.setPitch(getPitch()); 513 } 514 515 @Override 516 protected void stopImpl() { 517 AbstractSynthesisCallback synthesisCallback; 518 synchronized (this) { 519 synthesisCallback = mSynthesisCallback; 520 } 521 synthesisCallback.stop(); 522 TextToSpeechService.this.onStop(); 523 } 524 525 public String getLanguage() { 526 return getStringParam(Engine.KEY_PARAM_LANGUAGE, getDefaultLanguage()); 527 } 528 529 private boolean hasLanguage() { 530 return !TextUtils.isEmpty(getStringParam(Engine.KEY_PARAM_LANGUAGE, null)); 531 } 532 533 private String getCountry() { 534 if (!hasLanguage()) return getDefaultCountry(); 535 return getStringParam(Engine.KEY_PARAM_COUNTRY, ""); 536 } 537 538 private String getVariant() { 539 if (!hasLanguage()) return getDefaultVariant(); 540 return getStringParam(Engine.KEY_PARAM_VARIANT, ""); 541 } 542 543 private int getSpeechRate() { 544 return getIntParam(Engine.KEY_PARAM_RATE, getDefaultSpeechRate()); 545 } 546 547 private int getPitch() { 548 return getIntParam(Engine.KEY_PARAM_PITCH, Engine.DEFAULT_PITCH); 549 } 550 } 551 552 private class SynthesisToFileSpeechItem extends SynthesisSpeechItem { 553 private final File mFile; 554 555 public SynthesisToFileSpeechItem(String callingApp, Bundle params, String text, 556 File file) { 557 super(callingApp, params, text); 558 mFile = file; 559 } 560 561 @Override 562 public boolean isValid() { 563 if (!super.isValid()) { 564 return false; 565 } 566 return checkFile(mFile); 567 } 568 569 @Override 570 protected AbstractSynthesisCallback createSynthesisCallback() { 571 return new FileSynthesisCallback(mFile); 572 } 573 574 @Override 575 protected int playImpl() { 576 int status = super.playImpl(); 577 if (status == TextToSpeech.SUCCESS) { 578 dispatchUtteranceCompleted(); 579 } 580 return status; 581 } 582 583 /** 584 * Checks that the given file can be used for synthesis output. 585 */ 586 private boolean checkFile(File file) { 587 try { 588 if (file.exists()) { 589 Log.v(TAG, "File " + file + " exists, deleting."); 590 if (!file.delete()) { 591 Log.e(TAG, "Failed to delete " + file); 592 return false; 593 } 594 } 595 if (!file.createNewFile()) { 596 Log.e(TAG, "Can't create file " + file); 597 return false; 598 } 599 if (!file.delete()) { 600 Log.e(TAG, "Failed to delete " + file); 601 return false; 602 } 603 return true; 604 } catch (IOException e) { 605 Log.e(TAG, "Can't use " + file + " due to exception " + e); 606 return false; 607 } 608 } 609 } 610 611 private class AudioSpeechItem extends SpeechItem { 612 613 private final BlockingMediaPlayer mPlayer; 614 private AudioMessageParams mToken; 615 616 public AudioSpeechItem(String callingApp, Bundle params, Uri uri) { 617 super(callingApp, params); 618 mPlayer = new BlockingMediaPlayer(TextToSpeechService.this, uri, getStreamType()); 619 } 620 621 @Override 622 public boolean isValid() { 623 return true; 624 } 625 626 @Override 627 protected int playImpl() { 628 mToken = new AudioMessageParams(this, getCallingApp(), mPlayer); 629 mAudioPlaybackHandler.enqueueAudio(mToken); 630 return TextToSpeech.SUCCESS; 631 } 632 633 @Override 634 protected void stopImpl() { 635 // Do nothing. 636 } 637 } 638 639 private class SilenceSpeechItem extends SpeechItem { 640 private final long mDuration; 641 private SilenceMessageParams mToken; 642 643 public SilenceSpeechItem(String callingApp, Bundle params, long duration) { 644 super(callingApp, params); 645 mDuration = duration; 646 } 647 648 @Override 649 public boolean isValid() { 650 return true; 651 } 652 653 @Override 654 protected int playImpl() { 655 mToken = new SilenceMessageParams(this, getCallingApp(), mDuration); 656 mAudioPlaybackHandler.enqueueSilence(mToken); 657 return TextToSpeech.SUCCESS; 658 } 659 660 @Override 661 protected void stopImpl() { 662 // Do nothing. 663 } 664 } 665 666 @Override 667 public IBinder onBind(Intent intent) { 668 if (TextToSpeech.Engine.INTENT_ACTION_TTS_SERVICE.equals(intent.getAction())) { 669 return mBinder; 670 } 671 return null; 672 } 673 674 /** 675 * Binder returned from {@code #onBind(Intent)}. The methods in this class can be 676 * called called from several different threads. 677 */ 678 // NOTE: All calls that are passed in a calling app are interned so that 679 // they can be used as message objects (which are tested for equality using ==). 680 private final ITextToSpeechService.Stub mBinder = new ITextToSpeechService.Stub() { 681 682 public int speak(String callingApp, String text, int queueMode, Bundle params) { 683 if (!checkNonNull(callingApp, text, params)) { 684 return TextToSpeech.ERROR; 685 } 686 687 SpeechItem item = new SynthesisSpeechItem(intern(callingApp), params, text); 688 return mSynthHandler.enqueueSpeechItem(queueMode, item); 689 } 690 691 public int synthesizeToFile(String callingApp, String text, String filename, 692 Bundle params) { 693 if (!checkNonNull(callingApp, text, filename, params)) { 694 return TextToSpeech.ERROR; 695 } 696 697 File file = new File(filename); 698 SpeechItem item = new SynthesisToFileSpeechItem(intern(callingApp), 699 params, text, file); 700 return mSynthHandler.enqueueSpeechItem(TextToSpeech.QUEUE_ADD, item); 701 } 702 703 public int playAudio(String callingApp, Uri audioUri, int queueMode, Bundle params) { 704 if (!checkNonNull(callingApp, audioUri, params)) { 705 return TextToSpeech.ERROR; 706 } 707 708 SpeechItem item = new AudioSpeechItem(intern(callingApp), params, audioUri); 709 return mSynthHandler.enqueueSpeechItem(queueMode, item); 710 } 711 712 public int playSilence(String callingApp, long duration, int queueMode, Bundle params) { 713 if (!checkNonNull(callingApp, params)) { 714 return TextToSpeech.ERROR; 715 } 716 717 SpeechItem item = new SilenceSpeechItem(intern(callingApp), params, duration); 718 return mSynthHandler.enqueueSpeechItem(queueMode, item); 719 } 720 721 public boolean isSpeaking() { 722 return mSynthHandler.isSpeaking() || mAudioPlaybackHandler.isSpeaking(); 723 } 724 725 public int stop(String callingApp) { 726 if (!checkNonNull(callingApp)) { 727 return TextToSpeech.ERROR; 728 } 729 730 return mSynthHandler.stop(intern(callingApp)); 731 } 732 733 public String[] getLanguage() { 734 return onGetLanguage(); 735 } 736 737 /* 738 * If defaults are enforced, then no language is "available" except 739 * perhaps the default language selected by the user. 740 */ 741 public int isLanguageAvailable(String lang, String country, String variant) { 742 if (!checkNonNull(lang)) { 743 return TextToSpeech.ERROR; 744 } 745 746 return onIsLanguageAvailable(lang, country, variant); 747 } 748 749 /* 750 * There is no point loading a non default language if defaults 751 * are enforced. 752 */ 753 public int loadLanguage(String lang, String country, String variant) { 754 if (!checkNonNull(lang)) { 755 return TextToSpeech.ERROR; 756 } 757 758 return onLoadLanguage(lang, country, variant); 759 } 760 761 public void setCallback(String packageName, ITextToSpeechCallback cb) { 762 // Note that passing in a null callback is a valid use case. 763 if (!checkNonNull(packageName)) { 764 return; 765 } 766 767 mCallbacks.setCallback(packageName, cb); 768 } 769 770 private String intern(String in) { 771 // The input parameter will be non null. 772 return in.intern(); 773 } 774 775 private boolean checkNonNull(Object... args) { 776 for (Object o : args) { 777 if (o == null) return false; 778 } 779 return true; 780 } 781 }; 782 783 private class CallbackMap extends RemoteCallbackList<ITextToSpeechCallback> { 784 785 private final HashMap<String, ITextToSpeechCallback> mAppToCallback 786 = new HashMap<String, ITextToSpeechCallback>(); 787 788 public void setCallback(String packageName, ITextToSpeechCallback cb) { 789 synchronized (mAppToCallback) { 790 ITextToSpeechCallback old; 791 if (cb != null) { 792 register(cb, packageName); 793 old = mAppToCallback.put(packageName, cb); 794 } else { 795 old = mAppToCallback.remove(packageName); 796 } 797 if (old != null && old != cb) { 798 unregister(old); 799 } 800 } 801 } 802 803 public void dispatchUtteranceCompleted(String packageName, String utteranceId) { 804 ITextToSpeechCallback cb; 805 synchronized (mAppToCallback) { 806 cb = mAppToCallback.get(packageName); 807 } 808 if (cb == null) return; 809 try { 810 cb.utteranceCompleted(utteranceId); 811 } catch (RemoteException e) { 812 Log.e(TAG, "Callback failed: " + e); 813 } 814 } 815 816 @Override 817 public void onCallbackDied(ITextToSpeechCallback callback, Object cookie) { 818 String packageName = (String) cookie; 819 synchronized (mAppToCallback) { 820 mAppToCallback.remove(packageName); 821 } 822 mSynthHandler.stop(packageName); 823 } 824 825 @Override 826 public void kill() { 827 synchronized (mAppToCallback) { 828 mAppToCallback.clear(); 829 super.kill(); 830 } 831 } 832 833 } 834 835} 836