import java.util.Locale; import android.app.Activity; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private TextToSpeech tts; private Button btnSpeak; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnSpeak = (Button) findViewById(R.id.btnSpeak); btnSpeak.setOnClickListener(new MyOnClickListener()); //1.创建TextToSpeech对象,创建时传入OnInitListener监听器监听创建是否成功 tts = new TextToSpeech(this, new MyOnInitialListener()); } class MyOnInitialListener implements OnInitListener { @Override public void onInit(int status) { //2.设置TextToSpeech所使用语言、国家选项,通过返回值判断TTS是否支持该语言、国家选项 tts.setLanguage(Locale.ENGLISH); } } class MyOnClickListener implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnSpeak: //3.调用speak()或synthesizeToFile方法 tts.speak("Hello,I am TTS ", TextToSpeech.QUEUE_FLUSH, null); break; default: break; } } } @Override protected void onDestroy() { super.onDestroy(); if (tts != null) { //4.关闭TTS,回收资源 tts.shutdown(); } } }