您的位置:首页 > 移动开发 > Android开发

android自学之TextToSpeech实现文字向语音的转换

2013-04-14 10:24 686 查看
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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息