使用TextToSpeech 可以朗读文本,要先初始化TextToSpeech 对象,通过实现TextToSpeech.OnInitListener
接口来检测初始化状态成功与否(设置语言等动作是否成功),初始化成功后,才可以使用,用完该对象后,要调用shutdown方法,释放TextToSpeech (TTS)引擎占用的资源
package com.zhou.activity;
import java.util.Locale;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class TextToSpeechActivity extends Activity implements TextToSpeech.OnInitListener{
private static final String TAG = "TextToSpeechDemo";
private TextToSpeech mTts;
private Button mAgainButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_to_speech);
// 初始化TextToSpeech对象. 是一个异步操作.
// 初始化监听对象,在完成初始化时调用
mTts = new TextToSpeech(this,this);
//取得按钮
mAgainButton = (Button) findViewById(R.id.again_button);
//为按钮设置单击事件
mAgainButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sayHello();
}
});
}
@Override
public void onDestroy() {
if (mTts != null) {
//停止TextToSpeech
mTts.stop();
//释放TextToSpeech占用的资源
mTts.shutdown();
}
super.onDestroy();
}
//实现TextToSpeech.OnInitListener接口.
public void onInit(int status) {
//状态成功
if (status == TextToSpeech.SUCCESS) {
//设置语言
int result = mTts.setLanguage(Locale.US);
//(我试了中文,不好使????)
// int result = mTts.setLanguage(Locale.CHINA);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
// 如果不支持该语言
Log.e(TAG, "Language is not available.");
} else {
// TTS 引擎已经成功初始化
//按钮设置为可点击
mAgainButton.setEnabled(true);
//发音朗读
sayHello();
}
} else {
// 初始化失败
Log.e(TAG, "Could not initialize TextToSpeech.");
}
}
private static final Random RANDOM = new Random();
private static final String[] HELLOS = {
"Hello",
"Salutations",
"Greetings",
"Howdy",
"What's crack-a-lackin?",
"That explains the stench!"
};
//尝试朗读中文,失败了,语言设置为中国的也不行
// private static final String[] HELLOS = {
// "中国",
// "北京",
// "上海",
// "吉林",
// "辽宁",
// "北京欢迎你"
// };
private void sayHello() {
// Select a random hello.
int helloLength = HELLOS.length;
String hello = HELLOS[RANDOM.nextInt(helloLength)];
//朗读
mTts.speak(hello,TextToSpeech.QUEUE_FLUSH, null);
}
}