- package com.example.texttospeechexcercise;
- import java.util.Locale;
- import java.util.Random;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.Toast;
- import android.speech.tts.TextToSpeech;
- import android.text.StaticLayout;
- public class MainActivity extends Activity implements TextToSpeech.OnInitListener{
- String[] words=new String[]{"hello","dog","cat","bye"};
- //static final Random RANDOM=new Random();
- private TextToSpeech tSpeech;
- private Button button;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- button=(Button) findViewById(R.id.button1);
- tSpeech=new TextToSpeech(getApplicationContext(), this);
- button.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- sayHello();
- }
- });
- }
- private void sayHello() {
- // TODO Auto-generated method stub
- int size=words.length;
- //返回一個僞隨機數,它是取自此隨機數生成器序列的、在 0(包括)和指定值(不包括)之間均勻分佈的 int 值。
- //nextInt 的常規協定是,僞隨機地生成並返回指定範圍中的一個 int 值。所有可能的 n 個 int 值的生成概率(大致)相同。
- int i=new Random().nextInt(size);
- String word=words[i];
- tSpeech.speak(word, TextToSpeech.QUEUE_FLUSH, null);
- }
- @Override
- protected void onDestroy() {
- // TODO Auto-generated method stub
- if (tSpeech!=null) {
- tSpeech.stop();
- tSpeech.shutdown();
- }
- super.onDestroy();
- }
- @Override
- public void onInit(int status) {
- // TODO Auto-generated method stub
- if (status==TextToSpeech.SUCCESS) {
- int result=tSpeech.setLanguage(Locale.US);
- if (result==TextToSpeech.LANG_MISSING_DATA||result==TextToSpeech.LANG_NOT_SUPPORTED) {
- Toast.makeText(getApplicationContext(), "Language is not available.",1000).show();
- }
- else {
- button.setEnabled(true);
- sayHello();
- }
- }else {
- Toast.makeText(getApplicationContext(), "init failed", 1000).show();
- }
- }
- }