PageRenderTime 67ms CodeModel.GetById 11ms app.highlight 50ms RepoModel.GetById 1ms app.codeStats 1ms

/tts/src/com/google/tts/TTS.java

http://eyes-free.googlecode.com/
Java | 616 lines | 325 code | 38 blank | 253 comment | 35 complexity | a6b50600517640ebf9e22b105fe69d5d MD5 | raw file
  1/*
  2 * Copyright (C) 2008 Google Inc.
  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 com.google.tts;
 17
 18import android.content.ComponentName;
 19import android.content.Context;
 20import android.content.Intent;
 21import android.content.ServiceConnection;
 22import android.content.pm.PackageManager;
 23import android.content.pm.ResolveInfo;
 24import android.content.pm.PackageManager.NameNotFoundException;
 25import android.os.IBinder;
 26import android.os.RemoteException;
 27import android.util.Log;
 28
 29/**
 30 * Synthesizes speech from text. This abstracts away the complexities of using
 31 * the TTS service such as setting up the IBinder connection and handling
 32 * RemoteExceptions, etc.
 33 * 
 34 * The TTS should always be safe the use; if the user does not have the
 35 * necessary TTS apk installed, the behavior is that all calls to the TTS act as
 36 * no-ops.
 37 * 
 38 * @author clchen@google.com (Charles L. Chen)
 39 * @deprecated - Use TextToSpeechBeta instead
 40 */
 41@Deprecated
 42public class TTS {
 43  // This is the minimum version of the TTS service that is needed by this
 44  // version of the library stub.
 45  private final static int MIN_VER = 10;
 46
 47  /**
 48   * Called when the TTS has initialized
 49   * 
 50   * The InitListener must implement the onInit function. onInit is passed the
 51   * version number of the TTS library that the user has installed; since this
 52   * is called when the TTS has started, it is a good time to make sure that the
 53   * user's TTS library is up to date.
 54   */
 55  public interface InitListener {
 56    public void onInit(int version);
 57  }
 58
 59  /**
 60   * Called when the TTS has finished speaking by itself (ie, speaking finished
 61   * without being canceled).
 62   * 
 63   * The InitListener must implement the onInit function. onInit is passed the
 64   * version number of the TTS library that the user has installed; since this
 65   * is called when the TTS has started, it is a good time to make sure that the
 66   * user's TTS library is up to date.
 67   */
 68  public interface SpeechCompletedListener {
 69    public void onSpeechCompleted();
 70  }
 71
 72  private ServiceConnection serviceConnection; // Connection needed for the TTS
 73  private ITTS itts;
 74  private Context ctx;
 75  private InitListener cb = null;
 76  private int version = -1;
 77  private boolean started = false;
 78  private boolean showInstaller = false;
 79  private TTSVersionAlert versionAlert = null;
 80
 81  private ITTSCallback ittscallback;
 82  private SpeechCompletedListener speechCompletedCallback = null;
 83
 84  /**
 85   * The constructor for the TTS.
 86   * 
 87   * @param context The context
 88   * @param callback The InitListener that should be called when the TTS has
 89   *        initialized successfully.
 90   * @param displayInstallMessage Boolean indicating whether or not an
 91   *        installation prompt should be displayed to users who do not have the
 92   *        TTS library. If this is true, a generic alert asking the user to
 93   *        install the TTS will be used. If you wish to specify the exact
 94   *        message of that prompt, please use TTS(Context context, InitListener
 95   *        callback, TTSVersionAlert alert) as the constructor instead.
 96   */
 97  public TTS(Context context, InitListener callback, boolean displayInstallMessage) {
 98    showInstaller = displayInstallMessage;
 99    ctx = context;
100    cb = callback;
101    if (dataFilesCheck()) {
102      initTts();
103    }
104  }
105
106  /**
107   * The constructor for the TTS.
108   * 
109   * @param context The context
110   * @param callback The InitListener that should be called when the TTS has
111   *        initialized successfully.
112   * @param alert The TTSVersionAlert to be displayed
113   */
114  public TTS(Context context, InitListener callback, TTSVersionAlert alert) {
115    showInstaller = true;
116    versionAlert = alert;
117    ctx = context;
118    cb = callback;
119    if (dataFilesCheck()) {
120      initTts();
121    }
122  }
123
124  public void setOnSpeechCompletedListener(final SpeechCompletedListener listener) {
125    speechCompletedCallback = listener;
126  }
127
128  private boolean dataFilesCheck() {
129    if (!ConfigurationManager.allFilesExist()) {
130      // Treat missing voice data as the same as not having the TTS
131      // installed.
132      // If the developer wants to fail quietly, then just quit if there
133      // are
134      // missing voice data files.
135      if (!showInstaller) {
136        return false;
137      }
138      try {
139        int flags = Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY;
140        Context myContext = ctx.createPackageContext("com.google.tts", flags);
141        Class<?> appClass =
142            myContext.getClassLoader().loadClass("com.google.tts.ConfigurationManager");
143        Intent intent = new Intent(myContext, appClass);
144        ctx.startActivity(intent);
145        return false;
146      } catch (NameNotFoundException e) {
147        // Just let it fail through; this exception means that the
148        // TTS apk has not been installed and this case will be handled
149        // in the initTts function
150        e.printStackTrace();
151      } catch (ClassNotFoundException e) {
152        e.printStackTrace();
153      }
154    }
155    return true;
156  }
157
158  private void initTts() {
159    started = false;
160
161    // Initialize the TTS, run the callback after the binding is successful
162    serviceConnection = new ServiceConnection() {
163      public void onServiceConnected(ComponentName name, IBinder service) {
164        itts = ITTS.Stub.asInterface(service);
165        try {
166          version = itts.getVersion();
167          // The TTS service must be at least the min version needed
168          // by the
169          // library stub. Do not try to run the older TTS with the
170          // newer
171          // library stub as the newer library may reference methods
172          // which are
173          // unavailable and cause a crash.
174          if (version < MIN_VER) {
175            if (showInstaller) {
176              if (versionAlert != null) {
177                versionAlert.show();
178              } else {
179                new TTSVersionAlert(ctx, null, null, null).show();
180              }
181            }
182            return;
183          }
184
185          ittscallback = new ITTSCallback.Stub() {
186            public void markReached(String mark) throws RemoteException {
187              if (speechCompletedCallback != null) {
188                speechCompletedCallback.onSpeechCompleted();
189              }
190            }
191          };
192          itts.registerCallback(ittscallback);
193        } catch (RemoteException e) {
194          initTts();
195          return;
196        }
197
198        started = true;
199
200        // Load all the pre-recorded utterances that used to be a part of
201        // the old TTS.
202
203
204        // The callback can become null if the Android OS decides to
205        // restart the
206        // TTS process as well as whatever is using it. In such cases,
207        // do
208        // nothing - the error handling from the speaking calls will
209        // kick in
210        // and force a proper restart of the TTS.
211        if (cb != null) {
212          cb.onInit(version);
213        }
214      }
215
216      public void onServiceDisconnected(ComponentName name) {
217        itts = null;
218        cb = null;
219        started = false;
220      }
221    };
222
223    Intent intent = new Intent("android.intent.action.USE_TTS");
224    intent.addCategory("android.intent.category.TTS");
225    // Binding will fail only if the TTS doesn't exist;
226    // the TTSVersionAlert will give users a chance to install
227    // the needed TTS.
228    if (!ctx.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)) {
229      if (showInstaller) {
230        if (versionAlert != null) {
231          versionAlert.show();
232        } else {
233          new TTSVersionAlert(ctx, null, null, null).show();
234        }
235      }
236    }
237  }
238
239  /**
240   * Shuts down the TTS. It is good practice to call this in the onDestroy
241   * method of the Activity that is using the TTS so that the TTS is stopped
242   * cleanly.
243   */
244  public void shutdown() {
245    try {
246      ctx.unbindService(serviceConnection);
247    } catch (IllegalArgumentException e) {
248      // Do nothing and fail silently since an error here indicates that
249      // binding never succeeded in the first place.
250    }
251  }
252
253  /**
254   * Adds a mapping between a string of text and a sound resource in a package.
255   * 
256   * @see #TTS.speak(String text, int queueMode, String[] params)
257   * 
258   * @param text Example: <b><code>"south_south_east"</code></b><br/>
259   * 
260   * @param packagename Pass the packagename of the application that contains
261   *        the resource. If the resource is in your own application (this is
262   *        the most common case), then put the packagename of your application
263   *        here.<br/>
264   *        Example: <b>"com.google.marvin.compass"</b><br/>
265   *        The packagename can be found in the AndroidManifest.xml of your
266   *        application.
267   *        <p>
268   *        <code>&lt;manifest xmlns:android=&quot;...&quot;
269   *      package=&quot;<b>com.google.marvin.compass</b>&quot;&gt;</code>
270   *        </p>
271   * 
272   * @param resourceId Example: <b><code>R.raw.south_south_east</code></b>
273   */
274  public void addSpeech(String text, String packagename, int resourceId) {
275    if (!started) {
276      return;
277    }
278    try {
279      itts.addSpeech(text, packagename, resourceId);
280    } catch (RemoteException e) {
281      // TTS died; restart it.
282      started = false;
283      initTts();
284    } catch (NullPointerException e) {
285      // TTS died; restart it.
286      started = false;
287      initTts();
288    } catch (IllegalStateException e) {
289      // TTS died; restart it.
290      started = false;
291      initTts();
292    }
293  }
294
295  /**
296   * Adds a mapping between a string of text and a sound file. Using this, it is
297   * possible to add custom pronounciations for text.
298   * 
299   * @param text The string of text
300   * @param filename The full path to the sound file (for example:
301   *        "/sdcard/mysounds/hello.wav")
302   */
303  public void addSpeech(String text, String filename) {
304    if (!started) {
305      return;
306    }
307    try {
308      itts.addSpeechFile(text, filename);
309    } catch (RemoteException e) {
310      // TTS died; restart it.
311      started = false;
312      initTts();
313    } catch (NullPointerException e) {
314      // TTS died; restart it.
315      started = false;
316      initTts();
317    } catch (IllegalStateException e) {
318      // TTS died; restart it.
319      started = false;
320      initTts();
321    }
322  }
323
324  /**
325   * Speaks the string using the specified queuing strategy and speech
326   * parameters. Note that the speech parameters are not universally supported
327   * by all engines and will be treated as a hint. The TTS library will try to
328   * fulfill these parameters as much as possible, but there is no guarantee
329   * that the voice used will have the properties specified.
330   * 
331   * @param text The string of text to be spoken.
332   * @param queueMode The queuing strategy to use. Use 0 for no queuing, and 1
333   *        for queuing.
334   * @param params The array of speech parameters to be used. Currently, only
335   *        params[0] is defined - it is for setting the type of voice if the
336   *        engine allows it. Possible values are "VOICE_MALE", "VOICE_FEMALE",
337   *        and "VOICE_ROBOT". Note that right now only the pre-recorded voice
338   *        has this support - this setting has no effect on eSpeak.
339   */
340  public void speak(String text, int queueMode, String[] params) {
341    Log.i("TTS received: ", text);
342    if (!started) {
343      return;
344    }
345    try {
346      itts.speak(text, queueMode, params);
347    } catch (RemoteException e) {
348      Log.e("TTS", "RemoteException error.");
349      // TTS died; restart it.
350      started = false;
351      initTts();
352    } catch (NullPointerException e) {
353      Log.e("TTS", "NullPointerException error.");
354      // TTS died; restart it.
355      started = false;
356      initTts();
357    } catch (IllegalStateException e) {
358      Log.e("TTS", "IllegalStateException error.");
359      // TTS died; restart it.
360      started = false;
361      initTts();
362    }
363  }
364
365  /**
366   * Plays the earcon using the specified queueing mode and parameters.
367   * 
368   * @param earcon The earcon that should be played
369   * @param queueMode 0 for no queue (interrupts all previous utterances), 1 for
370   *        queued
371   * @param params An ArrayList of parameters.
372   */
373  public void playEarcon(String earcon, int queueMode, String[] params) {
374    if (!started) {
375      return;
376    }
377    try {
378      itts.playEarcon(earcon, queueMode, params);
379    } catch (RemoteException e) {
380      // TTS died; restart it.
381      started = false;
382      initTts();
383    } catch (NullPointerException e) {
384      // TTS died; restart it.
385      started = false;
386      initTts();
387    } catch (IllegalStateException e) {
388      // TTS died; restart it.
389      started = false;
390      initTts();
391    }
392  }
393
394  /**
395   * Plays the earcon using the specified queueing mode and parameters.
396   * 
397   * @param earcon The TTSEarcon that should be played
398   * @param queueMode 0 for no queue (interrupts all previous utterances), 1 for
399   *        queued
400   * @param params An ArrayList of parameters.
401   */
402  public void playEarcon(TTSEarcon earcon, int queueMode, String[] params) {
403    playEarcon(earcon.name(), queueMode, params);
404  }
405
406  /**
407   * Returns whether or not the TTS is busy speaking.
408   * 
409   * @return Whether or not the TTS is busy speaking.
410   */
411  public boolean isSpeaking() {
412    if (!started) {
413      return false;
414    }
415    try {
416      return itts.isSpeaking();
417    } catch (RemoteException e) {
418      // TTS died; restart it.
419      started = false;
420      initTts();
421    } catch (NullPointerException e) {
422      // TTS died; restart it.
423      started = false;
424      initTts();
425    } catch (IllegalStateException e) {
426      // TTS died; restart it.
427      started = false;
428      initTts();
429    }
430    return false;
431  }
432
433  /**
434   * Stops speech from the TTS.
435   */
436  public void stop() {
437    if (!started) {
438      return;
439    }
440    try {
441      itts.stop();
442    } catch (RemoteException e) {
443      // TTS died; restart it.
444      started = false;
445      initTts();
446    } catch (NullPointerException e) {
447      // TTS died; restart it.
448      started = false;
449      initTts();
450    } catch (IllegalStateException e) {
451      // TTS died; restart it.
452      started = false;
453      initTts();
454    }
455  }
456
457  /**
458   * Returns the version number of the TTS library that the user has installed.
459   * 
460   * @return The version number of the TTS library that the user has installed.
461   */
462  public int getVersion() {
463    return version;
464  }
465
466  /**
467   * Sets the TTS engine to be used.
468   * 
469   * @param selectedEngine The TTS engine that should be used.
470   */
471  public void setEngine(TTSEngine selectedEngine) {
472    if (!started) {
473      return;
474    }
475    try {
476      itts.setEngine(selectedEngine.toString());
477    } catch (RemoteException e) {
478      // TTS died; restart it.
479      started = false;
480      initTts();
481    }
482  }
483
484  public void setEngine(String ttsEngineBinary) {
485    if (!started) {
486      return;
487    }
488    try {
489      itts.setEngine(ttsEngineBinary);
490    } catch (RemoteException e) {
491      // TTS died; restart it.
492      started = false;
493      initTts();
494    }
495  }
496
497
498
499  /**
500   * Sets the speech rate for the TTS engine.
501   * 
502   * Note that the speech rate is not universally supported by all engines and
503   * will be treated as a hint. The TTS library will try to use the specified
504   * speech rate, but there is no guarantee.
505   * 
506   * Currently, this will change the speech rate for the espeak engine, but it
507   * has no effect on any pre-recorded speech.
508   * 
509   * @param speechRate The speech rate for the TTS engine.
510   */
511  public void setSpeechRate(int speechRate) {
512    if (!started) {
513      return;
514    }
515    try {
516      itts.setSpeechRate(speechRate);
517    } catch (RemoteException e) {
518      // TTS died; restart it.
519      started = false;
520      initTts();
521    }
522  }
523
524  /**
525   * Sets the language for the TTS engine.
526   * 
527   * Note that the language is not universally supported by all engines and will
528   * be treated as a hint. The TTS library will try to use the specified
529   * language, but there is no guarantee.
530   * 
531   * Currently, this will change the language for the espeak engine, but it has
532   * no effect on any pre-recorded speech.
533   * 
534   * @param language The language to be used. The languages are specified by
535   *        their IETF language tags as defined by BCP 47. This is the same
536   *        standard used for the lang attribute in HTML. See:
537   *        http://en.wikipedia.org/wiki/IETF_language_tag
538   */
539  public void setLanguage(String language) {
540    if (!started) {
541      return;
542    }
543    try {
544      itts.setLanguage(language);
545    } catch (RemoteException e) {
546      // TTS died; restart it.
547      started = false;
548      initTts();
549    }
550  }
551
552  /**
553   * Speaks the given text using the specified queueing mode and parameters.
554   * 
555   * @param text The String of text that should be synthesized
556   * @param params An ArrayList of parameters. The first element of this array
557   *        controls the type of voice to use.
558   * @param filename The string that gives the full output filename; it should
559   *        be something like "/sdcard/myappsounds/mysound.wav".
560   * @return A boolean that indicates if the synthesis succeeded
561   */
562  public boolean synthesizeToFile(String text, String[] params, String filename) {
563    if (!started) {
564      return false;
565    }
566    try {
567      return itts.synthesizeToFile(text, params, filename);
568    } catch (RemoteException e) {
569      // TTS died; restart it.
570      started = false;
571      initTts();
572    } catch (NullPointerException e) {
573      // TTS died; restart it.
574      started = false;
575      initTts();
576    } catch (IllegalStateException e) {
577      // TTS died; restart it.
578      started = false;
579      initTts();
580    }
581    return false;
582  }
583
584  /**
585   * Displays an alert that prompts users to install the TTS that is available
586   * on the Market. This is useful if the application expects a newer version of
587   * the TTS than what the user has.
588   */
589  public void showVersionAlert() {
590    if (!started) {
591      return;
592    }
593    if (versionAlert != null) {
594      versionAlert.show();
595    } else {
596      new TTSVersionAlert(ctx, null, null, null).show();
597    }
598  }
599
600  /**
601   * Checks if the TTS service is installed or not
602   * 
603   * @return A boolean that indicates whether the TTS service is installed
604   */
605  public static boolean isInstalled(Context ctx) {
606    PackageManager pm = ctx.getPackageManager();
607    Intent intent = new Intent("android.intent.action.USE_TTS");
608    intent.addCategory("android.intent.category.TTS");
609    ResolveInfo info = pm.resolveService(intent, 0);
610    if (info == null) {
611      return false;
612    }
613    return true;
614  }
615
616}