实现步骤:
- 创建TextToSpeech对象,创建时传入OnInitListener监听器
- 设置TextToSpeech所使用的语言、国家选项
- 调用speak()或synthesizeToFile方法
- 关闭TTS,回收资源
- 在布局中加入EditText用于获取文字,加入Button用于控制播放或存储合成的声音文件
- 代码:
TextToSpeech textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE && result != TextToSpeech.LANG_AVAILABLE) {
Toast.makeText(MainActivity.this, "暂不支持该语言", Toast.LENGTH_SHORT).show();
}
}
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab)
fab.setOnClickListener(new View.OnClickListener() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View view) {
textToSpeech.setSpeechRate(1)
textToSpeech.speak(editText.getText().toString(), TextToSpeech.QUEUE_ADD, null, "speech")
Snackbar.make(view, "是否存储该声音文件", Snackbar.LENGTH_LONG)
.setAction("存储", new View.OnClickListener() {
@Override
public void onClick(View v) {
textToSpeech.synthesizeToFile(editText.getText().toString(), null, new File("/mnt/sdcard/sound.mp3"), "record")
Toast.makeText(MainActivity.this, "存储成功", Toast.LENGTH_SHORT).show()
}
}).show()
}
})
protected void onDestroy() {
super.onDestroy();
if (textToSpeech != null) {
textToSpeech.shutdown();
}
}