您的位置:首页 > 移动开发 > Android开发

Android中使用TTS(TextToSpeech)将文字转为语音

2016-05-08 21:21 896 查看

实现步骤:

创建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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: