权限
页面
JAVA代码
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
private TextToSpeech textToSpeech = null;
private EditText editText;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.text1);
button = findViewById(R.id.btn_read);
textToSpeech = new TextToSpeech(this, this);
}
public void read(View view) {
if (textToSpeech != null && !textToSpeech.isSpeaking()) {
// 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
textToSpeech.setPitch(0.5f);
//设定语速 ,默认1.0正常语速
textToSpeech.setSpeechRate(1.5f);
//朗读,注意这里三个参数的added in API level 4 四个参数的added in API level 21
Bundle bundle = new Bundle();
bundle.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_NOTIFICATION);//设置音频通道
textToSpeech.speak(editText.getText().toString(), TextToSpeech.QUEUE_FLUSH, bundle,"1");
}
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
int result = textToSpeech.setLanguage(Locale.CHINA);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Toast.makeText(this, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onStop() {
super.onStop();
textToSpeech.stop(); // 不管是否正在朗读TTS都被打断
textToSpeech.shutdown(); // 关闭,释放资源
}
}