Android 文字轉語音 text to speech

摘要:Android 文字轉語音 text to speech

Android 1.6 開始有個 android.speech.tts.TextToSpeech 

關方部落格也有有寫

 

這裡用來檢查 tts 是否以安裝且啟用


Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);

 

繼承 OnInitListener


implements OnInitListener

 

做初始化 或 要求安裝TTS


@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// TODO Auto-generated method stub
		if (requestCode == MY_DATA_CHECK_CODE)
		{
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) // 如果TTS Engine有成功找到的話
			{
				tts = new TextToSpeech(this, this);
				// 宣告一個 TextToSpeech instance, 註冊android.speech.tts.TextToSpeech.OnInitListener
				// 當TTS Engine 初始完後會呼叫 onInit(int status)
				Log.d("onActivityResult", "onInit");
			}
			else // 如果 TTS 沒有安裝的話 , 要求安裝			
			{
				Intent installIntent = new Intent();
				installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);
			}
		}
	}

 

設定音調、速度及語言 (Google tts 及 Pico TTS 我都找不到中文...)


@Override
	public void onInit(int status)
	{
		if (status == TextToSpeech.SUCCESS)
		{
			tts.setPitch(1.0f); // 音調
			tts.setSpeechRate(1); // 速度
			int result = tts.setLanguage(Locale.US); // 語言
			
			if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
			{
				Log.e("TTS", "This Language is not supported");
			}
			else
			{
				btnSpeak.setEnabled(true);
				speakOut();
			}
		}
		else
		{
			Log.e("TTS", "Initilization Failed!");
		}
	}

 

念出來吧!!


private void speakOut()
	{
		String text = txtText.getText().toString();
		tts.speak(text, TextToSpeech.QUEUE_FLUSH, null); //TextToSpeech.QUEUE_ADD 為目前的念完才念
	}

 

最後記得銷燬


@Override
	public void onDestroy()
	{
		if (tts != null)
		{
			tts.stop();
			tts.shutdown();
		}
		super.onDestroy();
	}

 

有空再試試這個

http://translate.google.com/translate_tts?q=愛台灣啦&tl=zh-tw