一、活动布局只有读和停两个按钮
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/btn_read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="读" />
<Button
android:id="@+id/btn_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止"/>
</LinearLayout>
二、活动内代码
public class Main3Activity extends AppCompatActivity {
private Button speechBtn; // 按钮控制开始朗读
private Button stopBtn; // 停止朗读
private TextToSpeech textToSpeech; // TTS对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
speechBtn = (Button) findViewById(R.id.btn_read);
stopBtn = (Button) findViewById(R.id.btn_stop);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
//判断初始化是否成功
if (status == TextToSpeech.SUCCESS) {
textToSpeech.setSpeechRate(0.9f);//设定语速,默认1.0正常语速。
textToSpeech.setPitch(0.0f);// 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
int result = textToSpeech.setLanguage(Locale.CHINA);//语言设置中国
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(Main3Activity.this, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
}
}
}
});
speechBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (textToSpeech != null && !textToSpeech.isSpeaking()) {
//调用读取方法读取想要读取的值
String textRead="测量结果是99.99%";
textToSpeech.speak(textRead, TextToSpeech.QUEUE_FLUSH, null,"1");
}
}
});
stopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textToSpeech.stop(); // 不管是否正在朗读TTS都被打断
}
});
}
@Override
protected void onStop() {
super.onStop();
textToSpeech.shutdown(); // 关闭,释放资源
}
}