Java Code Examples for android.speech.tts.TextToSpeech#SUCCESS

The following examples show how to use android.speech.tts.TextToSpeech#SUCCESS . 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: TtsPlatformImpl.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to start speaking an utterance. If it returns true, will call back on
 * start and end.
 *
 * @param utteranceId A unique id for this utterance so that callbacks can be tied
 *     to a particular utterance.
 * @param text The text to speak.
 * @param lang The language code for the text (e.g., "en-US").
 * @param rate The speech rate, in the units expected by Android TextToSpeech.
 * @param pitch The speech pitch, in the units expected by Android TextToSpeech.
 * @param volume The speech volume, in the units expected by Android TextToSpeech.
 * @return true on success.
 */
@CalledByNative
private boolean speak(int utteranceId, String text, String lang,
                      float rate, float pitch, float volume) {
    if (!mInitialized) {
        mPendingUtterance = new PendingUtterance(this, utteranceId, text, lang, rate,
                pitch, volume);
        return true;
    }
    if (mPendingUtterance != null) mPendingUtterance = null;

    if (!lang.equals(mCurrentLanguage)) {
        mTextToSpeech.setLanguage(new Locale(lang));
        mCurrentLanguage = lang;
    }

    mTextToSpeech.setSpeechRate(rate);
    mTextToSpeech.setPitch(pitch);

    int result = callSpeak(text, volume, utteranceId);
    return (result == TextToSpeech.SUCCESS);
}
 
Example 2
Source File: TtsPlatformImpl.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to start speaking an utterance. If it returns true, will call back on
 * start and end.
 *
 * @param utteranceId A unique id for this utterance so that callbacks can be tied
 *     to a particular utterance.
 * @param text The text to speak.
 * @param lang The language code for the text (e.g., "en-US").
 * @param rate The speech rate, in the units expected by Android TextToSpeech.
 * @param pitch The speech pitch, in the units expected by Android TextToSpeech.
 * @param volume The speech volume, in the units expected by Android TextToSpeech.
 * @return true on success.
 */
@CalledByNative
private boolean speak(int utteranceId, String text, String lang,
                      float rate, float pitch, float volume) {
    if (!mInitialized) {
        mPendingUtterance = new PendingUtterance(this, utteranceId, text, lang, rate,
                pitch, volume);
        return true;
    }
    if (mPendingUtterance != null) mPendingUtterance = null;

    if (!lang.equals(mCurrentLanguage)) {
        mTextToSpeech.setLanguage(new Locale(lang));
        mCurrentLanguage = lang;
    }

    mTextToSpeech.setSpeechRate(rate);
    mTextToSpeech.setPitch(pitch);

    int result = callSpeak(text, volume, utteranceId);
    return (result == TextToSpeech.SUCCESS);
}
 
Example 3
Source File: TTS.java    From always-on-amoled with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onInit(int status) {
    if (toStopTTS) {
        try {
            tts.speak(" ", TextToSpeech.QUEUE_FLUSH, null);
        } catch (NullPointerException ignored) {
        }
        return;
    }
    if (status == TextToSpeech.SUCCESS) {
        if (!speaking) {
            SimpleDateFormat sdf;
            sdf = DateFormat.is24HourFormat(context) ? new SimpleDateFormat("HH mm", Locale.getDefault()) : new SimpleDateFormat("h mm aa", Locale.getDefault());
            String time = sdf.format(new Date());
            time = time.charAt(0) == '0' ? time.substring(1, time.length()) : time;

            tts.speak("The time is " + time, TextToSpeech.QUEUE_FLUSH, null);
            if (notificationCount > 0)
                tts.speak("You have " + notificationCount + " Notifications", TextToSpeech.QUEUE_ADD, null);
            tts.speak("Battery is at " + batteryReceiver.currentBattery + " percent", TextToSpeech.QUEUE_ADD, null);
            speaking = true;
            new Handler().postDelayed(() -> speaking = false, 4000);
        } else
            Utils.logDebug(MAIN_SERVICE_LOG_TAG, "Still speaking..");
    }
}
 
Example 4
Source File: MainActivity.java    From journaldev with MIT License 6 votes vote down vote up
@Override
public void onInit(int status) {

    if (status == TextToSpeech.SUCCESS) {
        int result = tts.setLanguage(Locale.US);

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Toast.makeText(getApplicationContext(), "Language not supported", Toast.LENGTH_SHORT).show();
        } else {
            button.setEnabled(true);
        }

    } else {
        Toast.makeText(getApplicationContext(), "Init failed", Toast.LENGTH_SHORT).show();
    }
}
 
Example 5
Source File: TtsHandler.java    From habpanelviewer with GNU General Public License v3.0 6 votes vote down vote up
private void doHandleCommand(String ttsCmd, String arg, Command cmd) {
    if (mStatus == TextToSpeech.SUCCESS) {
        if ("SPEAK".equalsIgnoreCase(ttsCmd)) {
            mTTS.speak(arg, TextToSpeech.QUEUE_ADD, null);
        } else {
            Locale l = new Locale(arg);

            if (mTTS.isLanguageAvailable(l) >= TextToSpeech.LANG_AVAILABLE) {
                mTTS.setLanguage(l);
            } else {
                cmd.failed("Given locale invalid: " + arg);
            }
        }
        cmd.finished();
    } else {
        cmd.failed("Could not initialize TTS engine!");
    }
}
 
Example 6
Source File: ReadAloudService.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onInit(int i) {
    if (i == TextToSpeech.SUCCESS) {
        int result = textToSpeech.setLanguage(Locale.CHINA);
        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            RxBus.get().post(RxBusTag.ALOUD_MSG, getString(R.string.tts_fix));
            //先停止朗读服务方便用户设置好后的重试
            ReadAloudService.stop(ReadAloudService.this);
            //跳转到文字转语音设置界面
            toTTSSetting();
        } else {
            textToSpeech.setOnUtteranceProgressListener(new ttsUtteranceListener());
            ttsInitSuccess = true;
            playTTS();
        }
    } else {
        RxBus.get().post(RxBusTag.ALOUD_MSG, getString(R.string.tts_init_failed));
        stopSelf();
    }
}
 
Example 7
Source File: TtsPlatformImpl.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
protected TtsPlatformImpl(long nativeTtsPlatformImplAndroid, Context context) {
    mInitialized = false;
    mNativeTtsPlatformImplAndroid = nativeTtsPlatformImplAndroid;
    mTextToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    ThreadUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initialize();
                        }
                    });
                }
            }
        });
    addOnUtteranceProgressListener();
}
 
Example 8
Source File: TtsActivity.java    From Android-Example with Apache License 2.0 5 votes vote down vote up
@Override
public void onInit(int status) {		
	if (status == TextToSpeech.SUCCESS) {
		Toast.makeText(TtsActivity.this, 
				"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
	}
	else if (status == TextToSpeech.ERROR) {
		Toast.makeText(TtsActivity.this, 
				"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
	}
}
 
Example 9
Source File: GameActivity.java    From TextFiction with Apache License 2.0 5 votes vote down vote up
@Override
public void onInit(int status) {
	ttsReady = (status == TextToSpeech.SUCCESS);
	if (ttsReady) {
		// Was the game faster to load?
		if (retainerFragment != null && retainerFragment.messageBuffer.size() > 0
				&& prefs.getBoolean("narrator", false)) {
			speaker.speak(
					retainerFragment.messageBuffer.get(retainerFragment.messageBuffer.size() - 1).message
							.toString(), TextToSpeech.QUEUE_FLUSH, null);
		}
	}
}
 
Example 10
Source File: PTextToSpeech.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
public PTextToSpeech(AppRunner appRunner) throws InterruptedException {

        mTts = new TextToSpeech(appRunner.getAppContext(), status -> {
            if (status == TextToSpeech.SUCCESS) {
                mTts.setLanguage(Locale.getDefault());
            } else {
                MLog.d(TAG, "Could not initialize TextToSpeech.");
            }
        });
    }
 
Example 11
Source File: MainActivity.java    From Beginner-Level-Android-Studio-Apps with GNU General Public License v3.0 5 votes vote down vote up
public void createTTS()
{
    t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int i) {
            if(i==TextToSpeech.SUCCESS)
            {
                t1.setLanguage(Locale.ENGLISH);
            }
        }
    });
}
 
Example 12
Source File: ReadAloudService.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onInit(int i) {
    if (i == TextToSpeech.SUCCESS) {
        textToSpeech.setLanguage(Locale.CHINA);
        textToSpeech.setOnUtteranceProgressListener(new ttsUtteranceListener());
        ttsInitSuccess = true;
        playTTS();
    } else {
        mainHandler.post(() -> Toast.makeText(ReadAloudService.this, getString(R.string.tts_init_failed), Toast.LENGTH_SHORT).show());
        ReadAloudService.this.stopSelf();
    }
}
 
Example 13
Source File: NaviVoice.java    From PocketMaps with MIT License 5 votes vote down vote up
private OnInitListener createInitListener()
{
  OnInitListener initList = new OnInitListener()
  {
    @Override
    public void onInit(int result)
    {
      if (result==TextToSpeech.SUCCESS) { ttsReady = true; }
    }
  };
  return initList;
}
 
Example 14
Source File: MainActivity.java    From CT_Android_demos with GNU General Public License v3.0 5 votes vote down vote up
@Override  
public void onInit(int status){  
    // �ж��Ƿ�ת���ɹ�  
    if (status == TextToSpeech.SUCCESS){  
        //Ĭ���趨����Ϊ���ģ�ԭ����androidò�Ʋ�֧�����ġ�
        int result = tts.setLanguage(Locale.CHINESE);  
        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){  
            Toast.makeText(MainActivity.this, R.string.notAvailable, Toast.LENGTH_SHORT).show();  
        }else{
            //��֧�����ľͽ���������ΪӢ��
            tts.setLanguage(Locale.US);
        }  
    }  
}
 
Example 15
Source File: MainActivity.java    From reader with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);

	mTakePhoto = (Button) findViewById(R.id.take_photo);
	mImageView = (ImageView) findViewById(R.id.imageview);
	speak1 = (Button) findViewById(R.id.speak1);
	responseText = (TextView) findViewById(R.id.textView1);

	mTakePhoto.setOnClickListener(this);
	speak1.setOnClickListener(this);
	
	tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
           @Override
           public void onInit(int status) {
               // TODO Auto-generated method stub
               if (status == TextToSpeech.SUCCESS)
               {
                   int result = tts.setLanguage(Locale.CHINA);
                   if (result == TextToSpeech.LANG_MISSING_DATA
                           || result == TextToSpeech.LANG_NOT_SUPPORTED)
                   {
                       Toast.makeText(getApplicationContext(), "Language is not available.",
                               Toast.LENGTH_SHORT).show();
                   }
               } else {
               	Toast.makeText(getApplicationContext(), "Language is available.",
                           Toast.LENGTH_SHORT).show();
               }
           }
       });
}
 
Example 16
Source File: TextToSpeechActivity.java    From codeexamples-android with Eclipse Public License 1.0 5 votes vote down vote up
public void onInit(int status) {
    // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
    if (status == TextToSpeech.SUCCESS) {
        // Set preferred language to US english.
        // Note that a language may not be available, and the result will indicate this.
        int result = mTts.setLanguage(Locale.US);
        // Try this someday for some interesting results.
        // int result mTts.setLanguage(Locale.FRANCE);
        if (result == TextToSpeech.LANG_MISSING_DATA ||
            result == TextToSpeech.LANG_NOT_SUPPORTED) {
           // Lanuage data is missing or the language is not supported.
            Log.e(TAG, "Language is not available.");
        } else {
            // Check the documentation for other possible result codes.
            // For example, the language may be available for the locale,
            // but not for the specified country and variant.

            // The TTS engine has been successfully initialized.
            // Allow the user to press the button for the app to speak again.
            mAgainButton.setEnabled(true);
            // Greet the user.
            sayHello();
        }
    } else {
        // Initialization failed.
        Log.e(TAG, "Could not initialize TextToSpeech.");
    }
}
 
Example 17
Source File: VoiceActivity.java    From BotLibre with Eclipse Public License 1.0 4 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
   public void onInit(int status) { 
       if (status == TextToSpeech.SUCCESS) {
           List<String> locales = new ArrayList<String>();
           if (MainActivity.voice.language != null) {
           	locales.add(MainActivity.voice.language);
           }
           locales.add(Locale.US.toString());
           locales.add(Locale.UK.toString());
           locales.add(Locale.FRENCH.toString());
           locales.add(Locale.GERMAN.toString());
           locales.add("ES");
           locales.add("PT");
           locales.add(Locale.ITALIAN.toString());
           locales.add(Locale.CHINESE.toString());
           locales.add(Locale.JAPANESE.toString());
           locales.add(Locale.KOREAN.toString());
           for (Locale locale : Locale.getAvailableLocales()) {
           	try {
            	int code = this.tts.isLanguageAvailable(locale);
                if (code != TextToSpeech.LANG_NOT_SUPPORTED) {
                	locales.add(locale.toString());
                }
           	} catch (Exception ignore) {}
           }
   		Spinner spin = (Spinner) findViewById(R.id.languageSpin);
   		ArrayAdapter adapter = new ArrayAdapter(this,
                   android.R.layout.simple_spinner_dropdown_item, locales.toArray());
   		spin.setAdapter(adapter);
           if (MainActivity.voice.language != null) {
           	spin.setSelection(locales.indexOf(MainActivity.voice.language));
           }
   		
           int result = this.tts.setLanguage(Locale.US); 
           if (result == TextToSpeech.LANG_MISSING_DATA
                   || result == TextToSpeech.LANG_NOT_SUPPORTED) {
               Log.e("TTS", "This Language is not supported");
           }
       } else {
           Log.e("TTS", "Initilization Failed!");
       }

   }
 
Example 18
Source File: VoiceActivity.java    From BotLibre with Eclipse Public License 1.0 4 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
   public void onInit(int status) { 
       if (status == TextToSpeech.SUCCESS) {
           List<String> locales = new ArrayList<String>();
           if (MainActivity.voice.language != null) {
           	locales.add(MainActivity.voice.language);
           }
           locales.add(Locale.US.toString());
           locales.add(Locale.UK.toString());
           locales.add(Locale.FRENCH.toString());
           locales.add(Locale.GERMAN.toString());
           locales.add("ES");
           locales.add("PT");
           locales.add(Locale.ITALIAN.toString());
           locales.add(Locale.CHINESE.toString());
           locales.add(Locale.JAPANESE.toString());
           locales.add(Locale.KOREAN.toString());
           for (Locale locale : Locale.getAvailableLocales()) {
           	try {
            	int code = this.tts.isLanguageAvailable(locale);
                if (code != TextToSpeech.LANG_NOT_SUPPORTED) {
                	locales.add(locale.toString());
                }
           	} catch (Exception ignore) {}
           }
   		Spinner spin = (Spinner) findViewById(R.id.languageSpin);
   		ArrayAdapter adapter = new ArrayAdapter(this,
                   android.R.layout.simple_spinner_dropdown_item, locales.toArray());
   		spin.setAdapter(adapter);
           if (MainActivity.voice.language != null) {
           	spin.setSelection(locales.indexOf(MainActivity.voice.language));
           }
   		
           int result = this.tts.setLanguage(Locale.US); 
           if (result == TextToSpeech.LANG_MISSING_DATA
                   || result == TextToSpeech.LANG_NOT_SUPPORTED) {
               Log.e("TTS", "This Language is not supported");
           }
       } else {
           Log.e("TTS", "Initilization Failed!");
       }

   }
 
Example 19
Source File: FailoverTextToSpeech.java    From talkback with Apache License 2.0 4 votes vote down vote up
/**
 * Handles TTS engine initialization.
 *
 * @param status The status returned by the TTS engine.
 */
@SuppressWarnings("deprecation")
private void handleTtsInitialized(int status) {
  if (mTempTts == null) {
    LogUtils.e(TAG, "Attempted to initialize TTS more than once!");
    return;
  }

  final TextToSpeech tempTts = mTempTts;
  final String tempTtsEngine = mTempTtsEngine;

  mTempTts = null;
  mTempTtsEngine = null;

  if (status != TextToSpeech.SUCCESS) {
    attemptTtsFailover(tempTtsEngine);
    return;
  }

  final boolean isSwitchingEngines = (mTts != null);

  if (isSwitchingEngines) {
    TextToSpeechUtils.attemptTtsShutdown(mTts);
  }

  mTts = tempTts;
  mTts.setOnUtteranceProgressListener(mUtteranceProgressListener);

  if (tempTtsEngine == null) {
    mTtsEngine = TextToSpeechCompatUtils.getCurrentEngine(mTts);
  } else {
    mTtsEngine = tempTtsEngine;
  }

  updateDefaultLocale();

  mTts.setAudioAttributes(
      new AudioAttributes.Builder()
          .setUsage(AudioAttributes.USAGE_ASSISTANCE_ACCESSIBILITY)
          .build());

  LogUtils.i(TAG, "Switched to TTS engine: %s", tempTtsEngine);

  for (FailoverTtsListener mListener : mListeners) {
    mListener.onTtsInitialized(isSwitchingEngines);
  }
}
 
Example 20
Source File: VoiceActivity.java    From BotLibre with Eclipse Public License 1.0 4 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
   public void onInit(int status) { 
       if (status == TextToSpeech.SUCCESS) {
           List<String> locales = new ArrayList<String>();
           if (MainActivity.voice.language != null) {
           	locales.add(MainActivity.voice.language);
           }
           locales.add(Locale.US.toString());
           locales.add(Locale.UK.toString());
           locales.add(Locale.FRENCH.toString());
           locales.add(Locale.GERMAN.toString());
           locales.add("ES");
           locales.add("PT");
           locales.add(Locale.ITALIAN.toString());
           locales.add(Locale.CHINESE.toString());
           locales.add(Locale.JAPANESE.toString());
           locales.add(Locale.KOREAN.toString());
           for (Locale locale : Locale.getAvailableLocales()) {
           	try {
            	int code = this.tts.isLanguageAvailable(locale);
                if (code != TextToSpeech.LANG_NOT_SUPPORTED) {
                	locales.add(locale.toString());
                }
           	} catch (Exception ignore) {}
           }
   		Spinner spin = (Spinner) findViewById(R.id.languageSpin);
   		ArrayAdapter adapter = new ArrayAdapter(this,
                   android.R.layout.simple_spinner_dropdown_item, locales.toArray());
   		spin.setAdapter(adapter);
           if (MainActivity.voice.language != null) {
           	spin.setSelection(locales.indexOf(MainActivity.voice.language));
           }
   		
           int result = this.tts.setLanguage(Locale.US); 
           if (result == TextToSpeech.LANG_MISSING_DATA
                   || result == TextToSpeech.LANG_NOT_SUPPORTED) {
               Log.e("TTS", "This Language is not supported");
           }
       } else {
           Log.e("TTS", "Initilization Failed!");
       }

   }