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(); } }
相关文章推荐
- ubuntu kylin14.04 上 android 5.1.1源码下载,编译
- Android 高效加载图片
- android打开相册选取图片或打开相机拍照并进行裁剪
- Android View绘制回调方法流程
- 关于Android应用的资源,国际化和资源自适应
- android audioflinger
- Android 中的 Service 全面总结
- Android.mk的使用
- Android使用ListView将数据显示到手机屏幕上
- Android文件读写操作--读取Assets中的文件数据
- Android常见漏洞
- Android动画--属性动画Property Animation
- Android Notification自定义PendingIntent 详解
- How to Enable USB Debugging Mode on Android
- 解决android调用系统相机拍照保存时onActivityResult中data为null的问题
- android sdk manager 说明
- Android动画--帧动画和补间动画
- Android总结 - Service
- android property
- Android 读取指定路径文件