Android開発爆笑記

レセプターのソフト&ハード開発備忘録

AndroidのTextToSpeech開発

Androidに喋らせる!

(1)MainActivityの内で変数宣言をする。
  TextToSpeech tts;

(2)MainActivity のクラス宣言部に
「implements TextToSpeech.OnInitListener」を手入力する。

(3)onCreate関数ないでインスタンス作成
  tts = new TextToSpeech(this, this);

(4)onDestroy関数内でインスタンス終了
  tts.shutdown();

(5)onInit関数内に定石入力
  if (TextToSpeech.SUCCESS == status) {
    Locale locale = Locale.JAPAN; //<-ここで言語を変える
    if (tts.isLanguageAvailable(locale) >= TextToSpeech.LANG_AVAILABLE) {
      tts.setLanguage(locale);
      isSpeech=true;
    } else {
      Toast.makeText(getApplicationContext(), "Error SetLocale", Toast.LENGTH_SHORT);
    }
  } else {
    Toast.makeText(getApplicationContext(), "Error Init", Toast.LENGTH_SHORT);
  }

(6)呼び出し関数を作る
  private void SpeechText(String aStr) {
    if (isSpeech) {
      if (0 < aStr.length()) {
        if (tts.isSpeaking()) {
          // 読み上げ中なら止める
          tts.stop();
        }
        // 読み上げ開始
        tts.speak(aStr, TextToSpeech.QUEUE_FLUSH, null);
      }
    }
  }


※importするか?の質問にはYesと答える。