2018年9月19日
并不主攻android,只是为了在开发嵌入式设备时方便使用调试而开发一些自己使用的android工具而已,所以在简书上只是记录一些可能以后用得上的代码,有些是之前网上找到比较能用的,比较早的就找不到出处了,以后还是把资料引用地址贴上来
TTS: TextToSpeech,文本转语音功能
这里实现文本播报+文本转换为wav文件
TextToSpeech textToSpeech;
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.CHINA);
if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE && result != TextToSpeech.LANG_AVAILABLE) {
Toast.makeText(MainActivity.this, "暂不支持该语言", Toast.LENGTH_SHORT).show();
}
}
}
});
语音播报:
textToSpeech.speak(editText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
保存为wav文件
File sdCardDir = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/TTStoMP3");
if (!sdCardDir.exists()) sdCardDir.mkdir(); //保存在储存TTStoMP3目录下
HashMap<String, String> myHashRender = new HashMap<String, String>();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, editText.getText().toString());
int r = textToSpeech.synthesizeToFile(editText.getText().toString(), myHashRender, sdCardDir+"/" + editText.getText().toString() + ".wav");
if (r == TextToSpeech.SUCCESS) {
//保存成功
}else {
//保存失败
}
最后,由于储存路径继续了读写,所以还需要相关权限:
<!-- 在SD卡中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 向SD卡写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />