主要方法
setLanguage:设置语言的类型
speak:传入文本播放声音
synthesizeToFile:传入文本保存为音频
shutdown:释放TextToSpeech资源
package prictise.lxm.prictise;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Locale;
/**
* 使用TextToSpeech实现自动朗读
*/
public class MainActivity extends Activity{
TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取界面视图
final EditText edTxtSpeak = (EditText)findViewById(R.id.edTxt_speak);
final Button btnSpeak = (Button)findViewById(R.id.btn_speak);
final Button btnSave = (Button)findViewById(R.id.btn_save);
textToSpeech = new TextToSpeech(this,new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
//初始化成功,设置语言
if(status == TextToSpeech.SUCCESS){
//设置语言为美式英语
int result = textToSpeech.setLanguage(Locale.US);
//设置语言为中文
// int result = textToSpeech.setLanguage(Locale.CHINA);
if(result != TextToSpeech.LANG_AVAILABLE &&
result != TextToSpeech.LANG_COUNTRY_AVAILABLE){ //不支持当前语言
Toast.makeText(MainActivity.this,"不支持" + textToSpeech.getLanguage().
getDisplayName(),Toast.LENGTH_SHORT).show();
//设置发音按钮不可用
btnSave.setEnabled(false);
btnSpeak.setEnabled(false);
}
}
}
});
//播放按钮
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textToSpeech.speak(edTxtSpeak.getText().toString(),TextToSpeech.QUEUE_ADD,null);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textToSpeech.synthesizeToFile(edTxtSpeak.getText().toString(),null,"speakUs");
}
});
}
protected void onDestroy() {
//释放tts
if(textToSpeech != null) {
textToSpeech.shutdown();
}
super.onDestroy();
}
}