android.speech.tts.TextToSpeech.Engine Java Examples

The following examples show how to use android.speech.tts.TextToSpeech.Engine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TtsEngineUtils.java    From brailleback with Apache License 2.0 7 votes vote down vote up
/**
 * Gets a list of all installed TTS engines sorted by priority (see
 * {@link #ENGINE_PRIORITY_COMPARATOR}).
 *
 * @return A sorted list of engine info objects. The list can be empty, but
 *         never {@code null}.
 */
public static List<TtsEngineInfo> getEngines(Context context) {
    final PackageManager pm = context.getPackageManager();
    final Intent intent = new Intent(Engine.INTENT_ACTION_TTS_SERVICE);
    final List<ResolveInfo> resolveInfos = pm.queryIntentServices(
            intent, PackageManager.MATCH_DEFAULT_ONLY);
    final List<TtsEngineInfo> engines = new ArrayList<TtsEngineInfo>(resolveInfos.size());

    for (ResolveInfo resolveInfo : resolveInfos) {
        final TtsEngineInfo engine = getEngineInfo(resolveInfo, pm);
        if (engine != null) {
            engines.add(engine);
        }
    }

    Collections.sort(engines, ENGINE_PRIORITY_COMPARATOR);

    return Collections.unmodifiableList(engines);
}
 
Example #2
Source File: TtsEngines.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a list of all installed TTS engines.
 *
 * @return A list of engine info objects. The list can be empty, but never {@code null}.
 */
public List<EngineInfo> getEngines() {
    PackageManager pm = mContext.getPackageManager();
    Intent intent = new Intent(Engine.INTENT_ACTION_TTS_SERVICE);
    List<ResolveInfo> resolveInfos =
            pm.queryIntentServices(intent, PackageManager.MATCH_DEFAULT_ONLY);
    if (resolveInfos == null) return Collections.emptyList();

    List<EngineInfo> engines = new ArrayList<EngineInfo>(resolveInfos.size());

    for (ResolveInfo resolveInfo : resolveInfos) {
        EngineInfo engine = getEngineInfo(resolveInfo, pm);
        if (engine != null) {
            engines.add(engine);
        }
    }
    Collections.sort(engines, EngineInfoComparator.INSTANCE);

    return engines;
}
 
Example #3
Source File: FailoverTextToSpeech.java    From talkback with Apache License 2.0 6 votes vote down vote up
/** Returns whether we need to attempt to use a fallback language. */
private boolean needsFallbackLocale() {
  // If the user isn't using Google TTS, or if they set a preferred
  // locale, we do not need to check locale support.
  if (!PACKAGE_GOOGLE_TTS.equals(mTtsEngine) || (mDefaultLocale != null)) {
    return false;
  }

  if (mTts == null) {
    return false;
  }

  // Otherwise, the TTS engine will attempt to use the system locale which
  // may not be supported. If the locale is embedded or advertised as
  // available, we're fine.
  final Set<String> features = mTts.getFeatures(mSystemLocale);
  return !(((features != null) && features.contains(Engine.KEY_FEATURE_EMBEDDED_SYNTHESIS))
      || !isNotAvailableStatus(mTts.isLanguageAvailable(mSystemLocale)));
}
 
Example #4
Source File: FailoverTextToSpeech.java    From talkback with Apache License 2.0 6 votes vote down vote up
private int speak(
    CharSequence text,
    HashMap<String, String> params,
    String utteranceId,
    float pitch,
    float rate,
    int stream,
    float volume) {
  Bundle bundle = new Bundle();

  if (params != null) {
    for (String key : params.keySet()) {
      bundle.putString(key, params.get(key));
    }
  }

  bundle.putInt(SpeechParam.PITCH, (int) (pitch * 100));
  bundle.putInt(SpeechParam.RATE, (int) (rate * 100));
  bundle.putInt(Engine.KEY_PARAM_STREAM, stream);
  bundle.putFloat(SpeechParam.VOLUME, volume);

  ensureQueueFlush();
  return mTts.speak(text, SPEECH_FLUSH_ALL, bundle, utteranceId);
}
 
Example #5
Source File: TtsEngineUtils.java    From brailleback with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the engine info for a given engine name. Note that engines are
 * identified by their package name.
 */
public static TtsEngineInfo getEngineInfo(Context context, String packageName) {
    if (packageName == null) {
        return null;
    }

    final PackageManager pm = context.getPackageManager();
    final Intent intent = new Intent(Engine.INTENT_ACTION_TTS_SERVICE).setPackage(packageName);
    final List<ResolveInfo> resolveInfos = pm.queryIntentServices(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
    if ((resolveInfos == null) || resolveInfos.isEmpty()) {
        return null;
    }

    // Note that the current API allows only one engine per
    // package name. Since the "engine name" is the same as
    // the package name.
    return getEngineInfo(resolveInfos.get(0), pm);
}
 
Example #6
Source File: TtsEngines.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the engine info for a given engine name. Note that engines are
 * identified by their package name.
 */
public EngineInfo getEngineInfo(String packageName) {
    PackageManager pm = mContext.getPackageManager();
    Intent intent = new Intent(Engine.INTENT_ACTION_TTS_SERVICE);
    intent.setPackage(packageName);
    List<ResolveInfo> resolveInfos = pm.queryIntentServices(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
    // Note that the current API allows only one engine per
    // package name. Since the "engine name" is the same as
    // the package name.
    if (resolveInfos != null && resolveInfos.size() == 1) {
        return getEngineInfo(resolveInfos.get(0), pm);
    }

    return null;
}
 
Example #7
Source File: TtsEngines.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * @return an intent that can launch the settings activity for a given tts engine.
 */
public Intent getSettingsIntent(String engine) {
    PackageManager pm = mContext.getPackageManager();
    Intent intent = new Intent(Engine.INTENT_ACTION_TTS_SERVICE);
    intent.setPackage(engine);
    List<ResolveInfo> resolveInfos = pm.queryIntentServices(intent,
            PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA);
    // Note that the current API allows only one engine per
    // package name. Since the "engine name" is the same as
    // the package name.
    if (resolveInfos != null && resolveInfos.size() == 1) {
        ServiceInfo service = resolveInfos.get(0).serviceInfo;
        if (service != null) {
            final String settings = settingsActivityFromServiceInfo(service, pm);
            if (settings != null) {
                Intent i = new Intent();
                i.setClassName(engine, settings);
                return i;
            }
        }
    }

    return null;
}
 
Example #8
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** Create AudioOutputParams from A {@link SynthesisRequest#getParams()} bundle */
static AudioOutputParams createFromParamsBundle(Bundle paramsBundle, boolean isSpeech) {
    if (paramsBundle == null) {
        return new AudioOutputParams();
    }

    AudioAttributes audioAttributes =
            (AudioAttributes) paramsBundle.getParcelable(
                    Engine.KEY_PARAM_AUDIO_ATTRIBUTES);
    if (audioAttributes == null) {
        int streamType = paramsBundle.getInt(
                Engine.KEY_PARAM_STREAM, Engine.DEFAULT_STREAM);
        audioAttributes = (new AudioAttributes.Builder())
                .setLegacyStreamType(streamType)
                .setContentType((isSpeech ?
                        AudioAttributes.CONTENT_TYPE_SPEECH :
                        AudioAttributes.CONTENT_TYPE_SONIFICATION))
                .build();
    }

    return new AudioOutputParams(
            paramsBundle.getInt(
                    Engine.KEY_PARAM_SESSION_ID,
                    AudioManager.AUDIO_SESSION_ID_GENERATE),
            paramsBundle.getFloat(
                    Engine.KEY_PARAM_VOLUME,
                    Engine.DEFAULT_VOLUME),
            paramsBundle.getFloat(
                    Engine.KEY_PARAM_PAN,
                    Engine.DEFAULT_PAN),
            audioAttributes);
}
 
Example #9
Source File: FailoverTextToSpeech.java    From talkback with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to speak the specified text.
 *
 * @param text to speak, must be under 3999 chars.
 * @param locale language to speak with. Use default language if it's null.
 * @param pitch to speak text in.
 * @param rate to speak text in.
 * @param params to the TTS.
 * @return The result of speaking the specified text.
 */
private int trySpeak(
    CharSequence text,
    @Nullable Locale locale,
    float pitch,
    float rate,
    HashMap<String, String> params,
    int stream,
    float volume) {
  if (mTts == null) {
    return TextToSpeech.ERROR;
  }

  float effectivePitch = (pitch * mDefaultPitch);
  float effectiveRate = (rate * mDefaultRate);

  String utteranceId = params.get(Engine.KEY_PARAM_UTTERANCE_ID);
  if ((locale != null) && !locale.equals(mLastUtteranceLocale)) {
    if (attemptSetLanguage(locale)) {
      mLastUtteranceLocale = locale;
    }
  } else if ((locale == null) && (mLastUtteranceLocale != null)) {
    ensureSupportedLocale();
    mLastUtteranceLocale = null;
  }
  int result = speak(text, params, utteranceId, effectivePitch, effectiveRate, stream, volume);

  if (result != TextToSpeech.SUCCESS) {
    ensureSupportedLocale();
  }

  LogUtils.d(TAG, "Speak call for %s returned %d", utteranceId, result);
  return result;
}
 
Example #10
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public IBinder onBind(Intent intent) {
    if (TextToSpeech.Engine.INTENT_ACTION_TTS_SERVICE.equals(intent.getAction())) {
        return mBinder;
    }
    return null;
}
 
Example #11
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** Create AudioOutputParams with default values */
AudioOutputParams() {
    mSessionId = AudioManager.AUDIO_SESSION_ID_GENERATE;
    mVolume = Engine.DEFAULT_VOLUME;
    mPan = Engine.DEFAULT_PAN;
    mAudioAttributes = null;
}
 
Example #12
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private String getCountry() {
    if (!hasLanguage()) return mDefaultLocale[1];
    return getStringParam(mParams, Engine.KEY_PARAM_COUNTRY, "");
}
 
Example #13
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private String getVariant() {
    if (!hasLanguage()) return mDefaultLocale[2];
    return getStringParam(mParams, Engine.KEY_PARAM_VARIANT, "");
}
 
Example #14
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public String getLanguage() {
    return getStringParam(mParams, Engine.KEY_PARAM_LANGUAGE, mDefaultLocale[0]);
}
 
Example #15
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public String getVoiceName() {
    return getStringParam(mParams, Engine.KEY_PARAM_VOICE_NAME, "");
}
 
Example #16
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@Override
public String getUtteranceId() {
    return getStringParam(mParams, Engine.KEY_PARAM_UTTERANCE_ID, null);
}
 
Example #17
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
int getPitch() {
    return getIntParam(mParams, Engine.KEY_PARAM_PITCH, getDefaultPitch());
}
 
Example #18
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private int getDefaultPitch() {
    return getSecureSettingInt(Settings.Secure.TTS_DEFAULT_PITCH, Engine.DEFAULT_PITCH);
}
 
Example #19
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private int getDefaultSpeechRate() {
    return getSecureSettingInt(Settings.Secure.TTS_DEFAULT_RATE, Engine.DEFAULT_RATE);
}
 
Example #20
Source File: SpeechControllerImpl.java    From talkback with Apache License 2.0 4 votes vote down vote up
private boolean processNextFragmentInternal() {
  if (currentFragmentIterator == null || !currentFragmentIterator.hasNext()) {
    return false;
  }
  if (mCurrentFeedbackItem == null) {
    // TODO: Probably due to asynchronous overlap of onFragmentCompleted() calling
    // processNextFragmentInternal(), and clearCurrentAndQueuedUtterances() setting
    // mCurrentFeedbackItem to null.
    return false;
  }

  FeedbackFragment fragment = currentFragmentIterator.next();
  EventId eventId = mCurrentFeedbackItem.getEventId();
  playEarconsFromFragment(fragment, eventId);
  playHapticsFromFragment(fragment, eventId);

  // Reuse the global instance of speech parameters.
  final HashMap<String, String> params = mSpeechParametersMap;
  params.clear();

  // Add all custom speech parameters.
  final Bundle speechParams = fragment.getSpeechParams();
  for (String key : speechParams.keySet()) {
    params.put(key, String.valueOf(speechParams.get(key)));
  }

  // Utterance ID, stream, and volume override item params.
  params.put(Engine.KEY_PARAM_UTTERANCE_ID, mCurrentFeedbackItem.getUtteranceId());
  params.put(Engine.KEY_PARAM_STREAM, String.valueOf(DEFAULT_STREAM));
  params.put(Engine.KEY_PARAM_VOLUME, String.valueOf(mSpeechVolume));

  final float pitch =
      mSpeechPitch * (mUseIntonation ? parseFloatParam(params, SpeechParam.PITCH, 1) : 1);
  final float rate =
      mSpeechRate * (mUseIntonation ? parseFloatParam(params, SpeechParam.RATE, 1) : 1);
  final CharSequence text;

  final boolean shouldSilenceFragment = shouldSilenceSpeech(mCurrentFeedbackItem);
  if (shouldSilenceFragment || TextUtils.isEmpty(fragment.getText())) {
    text = null;
  } else {
    text = fragment.getText();
  }
  final Locale locale = fragment.getLocale();

  final boolean preventDeviceSleep =
      mCurrentFeedbackItem.hasFlag(FeedbackItem.FLAG_NO_DEVICE_SLEEP);

  final String logText = (text == null) ? null : String.format("\"%s\"", text.toString());
  LogUtils.v(
      TAG,
      "Speaking fragment text %s with spans %s for event %s",
      logText,
      SpannableUtils.spansToStringForLogging(text),
      eventId);

  if (text != null && mCurrentFeedbackItem.hasFlag(FeedbackItem.FLAG_FORCED_FEEDBACK)) {
    mDelegate.onSpeakingForcedFeedback();
  }

  // It's okay if the utterance is empty, the fail-over TTS will
  // immediately call the fragment completion listener. This process is
  // important for things like continuous reading.
  mFailoverTts.speak(
      text, locale, pitch, rate, params, DEFAULT_STREAM, mSpeechVolume, preventDeviceSleep);

  if (mTtsOverlay != null) {
    mTtsOverlay.displayText(text);
  }

  return true;
}
 
Example #21
Source File: FailoverTextToSpeech.java    From talkback with Apache License 2.0 4 votes vote down vote up
/**
 * Speak the specified text.
 *
 * @param text The text to speak.
 * @param locale Language of the text.
 * @param pitch The pitch adjustment, in the range [0 ... 1].
 * @param rate The rate adjustment, in the range [0 ... 1].
 * @param params The parameters to pass to the text-to-speech engine.
 */
public void speak(
    CharSequence text,
    @Nullable Locale locale,
    float pitch,
    float rate,
    HashMap<String, String> params,
    int stream,
    float volume,
    boolean preventDeviceSleep) {

  String utteranceId = params.get(Engine.KEY_PARAM_UTTERANCE_ID);
  addRecentUtteranceId(utteranceId);

  // Handle empty text immediately.
  if (TextUtils.isEmpty(text)) {
    mHandler.onUtteranceCompleted(params.get(Engine.KEY_PARAM_UTTERANCE_ID), /* success= */ true);
    return;
  }

  int result;

  volume *= calculateVolumeAdjustment();

  if (preventDeviceSleep && mWakeLock != null && !mWakeLock.isHeld()) {
    mWakeLock.acquire();
  }

  Exception failureException = null;
  try {
    result = trySpeak(text, locale, pitch, rate, params, stream, volume);
  } catch (Exception e) {
    failureException = e;
    result = TextToSpeech.ERROR;
    allowDeviceSleep();
  }

  if (result == TextToSpeech.ERROR) {
    attemptTtsFailover(mTtsEngine);
  }

  if ((result != TextToSpeech.SUCCESS) && params.containsKey(Engine.KEY_PARAM_UTTERANCE_ID)) {
    if (failureException != null) {
      LogUtils.w(TAG, "Failed to speak %s due to an exception", text);
      failureException.printStackTrace();
    } else {
      LogUtils.w(TAG, "Failed to speak %s", text);
    }

    mHandler.onUtteranceCompleted(params.get(Engine.KEY_PARAM_UTTERANCE_ID), /* success= */ true);
  }
}
 
Example #22
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
int getSpeechRate() {
    return getIntParam(mParams, Engine.KEY_PARAM_RATE, getDefaultSpeechRate());
}
 
Example #23
Source File: TextToSpeechService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
boolean hasLanguage() {
    return !TextUtils.isEmpty(getStringParam(mParams, Engine.KEY_PARAM_LANGUAGE, null));
}
 
Example #24
Source File: TtsEngineUtils.java    From brailleback with Apache License 2.0 2 votes vote down vote up
/**
 * Returns whether speech synthesis using a specific language on the
 * specified TTS requires a network connection.
 *
 * @param tts The TTS engine to check.
 * @param language The language to check.
 * @return {@code true} if the language requires a network connection.
 */
public static boolean isNetworkRequiredForSynthesis(TextToSpeech tts, Locale language) {
    final Set<String> features = tts.getFeatures(language);
    return features.contains(Engine.KEY_FEATURE_NETWORK_SYNTHESIS) &&
            !features.contains(Engine.KEY_FEATURE_EMBEDDED_SYNTHESIS);
}